UDP communication in Java

1 UDP communication mechanism

The Internet protocol suite supports a connectionless transport protocol called User Datagram Protocol ( UDP ). Unlike the TCP protocol, UDP provides a way for applications to send encapsulated IP packets without establishing a connection. Before sending data, you need to perform a packet operation (using the DatagramPacket class) to send and receive data (using the DatagramSocket class).

When using UDP to transmit data, possible problems include:

Lost package;

out of order;

error packet;

Repeated sending of data packets.

Scenarios that usually require the use of UDP are mainly when the requirements for data flow are not high, such as video streaming, audio streaming, etc.

2 General steps for UDP communication programming

  • Create the client's DatagramSocket and define the port used by the client to receive messages;

  • Create a DatagramSocket on the server side and define the port used by the server to receive messages;

  • Create a DatagramPacket object on the server side to encapsulate the data packet to be sent;

  • The client sends the message;

  • The server receives the message.

3 server

The server uses DatagramSocketan object to receive data. When creating an object, you need to specify a port for receiving requests.

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpServer {
    public static void main(String[] args) {
        try {
            //创建服务端接收数据的 DatagramSocket 对象
            DatagramSocket datagramSocket = new DatagramSocket(5555);
            //创建数据缓冲区
            byte[] buff = new byte[1024];
            //创建数据报的包对象
            DatagramPacket packet = new DatagramPacket(buff, buff.length);
            //等待接收客户端发送的数据
            datagramSocket.receive(packet);
            //获取数据
            String input = new String(packet.getData(), 0, packet.getLength());

            System.out.println("接收到客户端的请求: " + input);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

When receiving requests from the client, a byte buffer is used, which can receive 1024 bytes of data at a time, which can reduce network IO operations.

The data flow between the server and the client uses DatagramPacketencapsulation, so when receiving data, this object should be used to receive it.

datagramSocket.receive(packet);The method is a blocking method. When no data is received, the program will wait here. After receiving the data, it will continue to execute the following code.

After receiving the byte data, if you do not want to use binary data directly, you need to convert the data.

When obtaining the received data, new String(packet.getData(), 0, packet.getLength())all the contents of the buffer are not read, because when the actual data read from the network card is less than the length of the buffer, the data is not available to the server. meaningful. We only need to take the actual received datagram.

4 clients

When creating the client, you also need to create a DatagramSocket object and specify the port for sending data. If the client is on the same machine as the server, the port should be different from the server.

When the client sends data, the data needs to be encapsulated into a DatagramPacket object, and the server IP and port for receiving the data need to be specified.

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.Scanner;

public class UdpClient {
    public static void main(String[] args) {
        try {
            //创建数据发送对象,并指定要发送数据的端口
            DatagramSocket socket = new DatagramSocket(5556);
            //将要发送的数据转换为字节数组
            Scanner scanner = new Scanner(System.in);
            String output = scanner.next();
            byte[] bytes = output.getBytes();
            //创建数据报的包对象
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, new InetSocketAddress("127.0.0.1", 5555));
            //发送消息
            socket.send(packet);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5 Communication

5.1 Do not start the server

When the server is not started and only the client is started to send data, the client sends the data normally without reporting an error.

image.png

It can be seen that the client did not check the server when sending data.

5.2 Start the server

image.png

This is one communication. If you want to establish multiple communications, you can add a loop on the server side. The method is similar to TCP communication.

Guess you like

Origin blog.csdn.net/QQ156881887/article/details/129854182