The use of JAVA UDP

To understand the use of UDP in java, we must first understand the UDP protocol:
UDP is a high-speed, connectionless data exchange method. In some applications, maintaining the fastest speed is more important than ensuring that every bit of data arrives correctly. For example, in real-time audio or video, lost packets only appear as interference. Interference is tolerable, but awkward pauses in the audio stream when TCP requests a retransmission or waits for a packet to arrive and it arrives late is unacceptable. In other applications, reliable transport can be implemented at the application layer. For example: if the client sends a short UDP request to the server, if no response is returned within the specified time, it will consider the packet lost. This is how the Domain Name System works. In fact, it is possible to implement a reliable file transfer protocol using UDP, and many people do: network file systems, simple FTP use the UDP protocol. In these protocols, the application is responsible for reliability. The UDP implementation in java is divided into two classes: DatagramPacket and DatagramSocket. The DatagramPacket class stuffs data bytes into a UDP packet, which is called a datagram. DatagramSocket to send this packet. To accept data, you can accept a DatagramPack object from the DatagramSocket, and then read the contents of the data from the packet.
This division of responsibilities differs from the Socket and ServerSocket used by TCP. First of all, UDP does not have the concept of a unique connection between two hosts, it does not need to know which remote host the other is. It can send information from one port to multiple hosts, but TCP cannot. Second, TCP sockets treat network links as streams: data is sent and received through input and output streams obtained from the socket. UDP doesn't support this, you're dealing with always single packets. All the data stuffed into a datagram is sent in packets that are either received as a group or all of them are discarded. One package is not necessarily related to the next. Given two packets, there is no way to know which will be sent first and which will be sent later. Unlike streams, which must provide an ordered queue of data, datagrams are swarmed to the receiver as quickly as possible.

The following will introduce the preliminary steps of UDP receiving and sending data in JAVA:
Send:
Use DatagramSocket(int port) to establish socket (suite word) service.
Pack the data into the DatagramPacket and send it
through the socket service (send() method) to
close the resource

    import java.io.IOException;  
    import java.net.*;  

    public class Send {  

        public static void main(String[] args)  {  

            DatagramSocket ds = null;  //建立套间字udpsocket服务  

            try {  
              ds = new DatagramSocket(8999);  //实例化套间字,指定自己的port  
            } catch (SocketException e) {  
                System.out.println("Cannot open port!");  
                System.exit(1);   
            }  

            byte[] buf= "Hello, I am sender!".getBytes();  //数据  
            InetAddress destination = null ;  
            try {  
                destination = InetAddress.getByName("192.168.1.5");  //需要发送的地址  
            } catch (UnknownHostException e) {  
                System.out.println("Cannot open findhost!");  
                System.exit(1);   
            }  
            DatagramPacket dp =   
                    new DatagramPacket(buf, buf.length, destination , 10000);    
            //打包到DatagramPacket类型中(DatagramSocket的send()方法接受此类,注意10000是接受地址的端口,不同于自己的端口!)  

            try {  
                ds.send(dp);  //发送数据  
            } catch (IOException e) {  
            }  
            ds.close();  
        }  
    }  

Receive:
Use DatagramSocket(int port) to establish a socket (suite word) service. (We noticed that this service can both receive and send), port specifies the monitor accepting port.
Define a data packet (DatagramPacket), store the received data, and use the method to extract the transmitted content. Store the received data into the packet defined above
through the receive method of
DatagramSocket. Use the method of DatagramPacket to extract the data.
Close the resource.
"`

import java.net.*;  
public class Rec {  

    public static void main(String[] args) throws Exception {  

        DatagramSocket ds = new DatagramSocket(10000);  //定义服务,监视端口上面的发送端口,注意不是send本身端口  

        byte[] buf = new byte[1024];//接受内容的大小,注意不要溢出  

        DatagramPacket dp = new DatagramPacket(buf,0,buf.length);//定义一个接收的包  

        ds.receive(dp);//将接受内容封装到包中  

        String data = new String(dp.getData(), 0, dp.getLength());//利用getData()方法取出内容  

        System.out.println(data);//打印内容  

        ds.close();//关闭资源     
    }  
}  
```

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325707957&siteId=291194637