在Java中实现UDP聊天室,你需要使用java.net
包中的DatagramSocket
类。以下是一个简单的UDP聊天室示例,包括一个服务器端和一个客户端。
服务器端代码:
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class UDPServer { public static void main(String[] args) throws IOException { int port = 12345; DatagramSocket socket = new DatagramSocket(port); System.out.println("Server is listening on port " + port); while (true) { byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); socket.receive(packet); String receivedMessage = new String(packet.getData(), 0, packet.getLength()); System.out.println("Received message: " + receivedMessage); String response = "Message received: " + receivedMessage; byte[] sendData = https://www.yisu.com/ask/response.getBytes();>客户端代码:
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class UDPClient { public static void main(String[] args) throws IOException { String serverAddress = "localhost"; int serverPort = 12345; DatagramSocket socket = new DatagramSocket(); System.out.println("Connected to server " + serverAddress + ":" + serverPort); Scanner scanner = new Scanner(System.in); while (true) { System.out.print("Enter your message: "); String message = scanner.nextLine(); byte[] sendData = https://www.yisu.com/ask/message.getBytes();"Server response: " + receivedMessage); } } }这个示例中,服务器端监听指定的端口,接收客户端发送的消息,并将接收到的消息原样发送回客户端。客户端连接到服务器,发送消息并接收服务器的响应。
请注意,这个示例仅用于演示目的,实际应用中可能需要考虑更多因素,例如多个客户端之间的通信、消息格式、错误处理等。