生成一个Java基于UDP协议的简单聊天程序
时间: 2024-02-25 17:57:16 浏览: 66
以下是一个基于UDP协议的简单聊天程序的Java代码示例:
服务端代码:
```java
import java.io.IOException;
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws IOException {
// 创建UDP套接字
DatagramSocket serverSocket = new DatagramSocket(8888);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
// 接收客户端发送的数据
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String message = new String(receivePacket.getData());
System.out.println("Received message from " + receivePacket.getAddress() + ": " + message);
// 发送响应数据给客户端
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
String responseMessage = "Hello from server!";
sendData = responseMessage.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
}
}
}
```
客户端代码:
```java
import java.io.IOException;
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws IOException {
// 创建UDP套接字
DatagramSocket clientSocket = new DatagramSocket();
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
// 发送数据给服务端
InetAddress serverAddress = InetAddress.getByName("127.0.0.1");
int serverPort = 8888;
String message = "Hello from client!";
sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, serverPort);
clientSocket.send(sendPacket);
// 接收服务端发送的响应数据
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String responseMessage = new String(receivePacket.getData());
System.out.println("Received message from " + receivePacket.getAddress() + ": " + responseMessage);
}
}
}
```
在这个聊天程序中,服务端和客户端均使用UDP套接字进行通信。服务端首先创建一个UDP套接字,并绑定到指定的端口号。然后进入一个无限循环,等待接收客户端发送的数据。当服务端接收到客户端发送的数据后,它会打印出接收到的消息,并将响应消息发送给客户端。
客户端创建一个UDP套接字,并指定服务端的IP地址和端口号,然后进入一个无限循环,等待用户输入要发送的消息。当客户端输入消息后,它会将消息发送给服务端,并等待服务端的响应。当客户端接收到服务端的响应后,它会打印出接收到的消息。
阅读全文