Java可以使用UDP协议来进行网络通信的示例
时间: 2023-07-30 12:10:20 浏览: 82
当使用UDP协议进行网络通信时,需要使用`DatagramSocket`和`DatagramPacket`两个类来实现。下面是一个Java使用UDP协议进行网络通信的示例代码:
服务器端代码:
```
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876); // 创建UDP socket并绑定端口号
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket); // 接收客户端请求
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket); // 发送响应给客户端
}
}
}
```
客户端代码:
```
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");
int port = 9876;
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = "hello server";
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
clientSocket.send(sendPacket); // 发送请求给服务器
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket); // 接收服务器响应
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
```
这个示例代码中,客户端向服务器发送一个字符串请求,服务器收到请求后将字符串转为大写并返回给客户端。
阅读全文