Java面向通信的UDP
时间: 2023-09-14 18:02:40 浏览: 99
在Java中,使用UDP进行通信需要使用`java.net`包中的`DatagramSocket`和`DatagramPacket`类。以下是一个简单的UDP通信示例:
服务端代码:
```java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received: " + sentence);
}
}
}
```
客户端代码:
```java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
String sentence = "Hello, server!";
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
clientSocket.close();
}
}
```
在这个示例中,服务端监听端口号为9876,并通过`DatagramSocket.receive()`方法接收客户端发送的数据包。客户端发送数据包到服务端的IP地址和端口号,通过`DatagramSocket.send()`方法发送数据包。
请注意,UDP协议是无连接的,因此不保证数据包会按照发送的顺序到达目标。此外,UDP协议也没有像TCP协议那样提供可靠性和流控制。因此,在使用UDP进行通信时,需要自己实现必要的错误处理和重传机制。
阅读全文