This article talks about using udp to do a simple sending and receiving in Java.
Code 1: Sender-demo2Sender.java
package udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException;
In the java network communication industry As Socket (socket) communication, both devices required for communication must have Socket installed.
Different protocols have different sockets (Sockets)
Features of UDP communication protocol:
1. Encapsulate the data For data packets, connectionless oriented.
2. The size of each data packet is limited to 64K
3. Because there is no connection, it is unreliable
4. Because there is no need to establish a connection, it is fast
5. UDP communication is not divided into server and client, only sender and receiver.
For example: property management walkie-talkie, FeiQ chat, games...
Socket under udp protocol:
DatagramSocket (udp socket service )
DatagramPacket(data packet class)
DatagramPacket(buf, length, address, port)
buf: sent data content
length: sent The size of the data content.
address: the destination IP address object sent
port: the port number.
Steps for using the sender:
1. Establish udp service.
2. Prepare the data, encapsulate the data into a data packet and send it. The data packet from the sending end must carry the IP address and port number.
3. Call the udp service and send data.
4. Close the resource.
/发送端 @SuppressWarnings("unused") public class demo1Sender { public static void main(String[] args) throws IOException { //建立udp的服务 DatagramSocket datagramSocket = new DatagramSocket(); //准备数据,把数据封装到数据包中。 String data = "这个是我第一个udp的例子.."; //创建了一个数据包 DatagramPacket packet = new DatagramPacket(data.getBytes(), data.getBytes().length,InetAddress.getLocalHost() , 9090); //调用udp的服务发送数据包 datagramSocket.send(packet); //关闭资源 ---实际上就是释放占用的端口号 datagramSocket.close(); } }
Code 2: Receiver-demo1Receive.java
package udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket;
Receiver usage steps
1. Establish udp service
2. Prepare empty data packets to receive data.
3. Call the udp service to receive data.
4. Close the resource
public class demo1Receive { public static void main(String[] args) throws IOException { //建立udp的服务 ,并且要监听一个端口。 DatagramSocket socket = new DatagramSocket(9090); //准备空的数据包用于存放数据。 byte[] buf = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length); // 1024 //调用udp的服务接收数据 socket.receive(datagramPacket); //receive是一个阻塞型的方法,没有接收到数据包之前会一直等待。 数据实际上就是存储到了byte的自己数组中了。 System.out.println("接收端接收到的数据:"+ new String(buf,0,datagramPacket.getLength())); // getLength() 获取数据包存储了几个字节。 System.out.println("receive阻塞了我,哈哈"); //关闭资源 socket.close(); } }
[Recommended course: Java Video Tutorial]
The above is the detailed content of java-Use udp to do a simple sending and receiving. For more information, please follow other related articles on the PHP Chinese website!