java udp简单聊天程序_Java基于UDP协议实现简单的聊天室程序
时间: 2024-03-21 11:43:58 浏览: 111
好的,这是一个简单的Java基于UDP协议实现的聊天室程序,可以供你参考:
服务端代码:
```
import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String args[]) {
DatagramSocket aSocket = null;
try {
aSocket = new DatagramSocket(6789);
byte[] buffer = new byte[1000];
System.out.println("Server is running...");
while (true) {
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
aSocket.receive(request);
String requestMessage = new String(request.getData()).trim();
System.out.println("Client : " + requestMessage);
String replyMessage = "Server : " + requestMessage;
DatagramPacket reply = new DatagramPacket(replyMessage.getBytes(), replyMessage.length(), request.getAddress(), request.getPort());
aSocket.send(reply);
}
} catch (SocketException e) {
System.out.println("Socket: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO: " + e.getMessage());
} finally {
if (aSocket != null)
aSocket.close();
}
}
}
```
客户端代码:
```
import java.net.*;
import java.io.*;
public class UDPClient {
public static void main(String args[]) {
DatagramSocket aSocket = null;
try {
aSocket = new DatagramSocket();
InetAddress aHost = InetAddress.getByName("localhost");
int serverPort = 6789;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Client : ");
String requestMessage = br.readLine();
DatagramPacket request = new DatagramPacket(requestMessage.getBytes(), requestMessage.length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
String replyMessage = new String(reply.getData()).trim();
System.out.println(replyMessage);
}
} catch (SocketException e) {
System.out.println("Socket: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO: " + e.getMessage());
} finally {
if (aSocket != null)
aSocket.close();
}
}
}
```
运行服务端代码后,再运行多个客户端代码即可实现简单的聊天室功能。
阅读全文