阅读量:0
要用Java编写一个简单的聊天室,你可以使用套接字编程(Socket Programming)。这里是一个基本的聊天室实现教程:
- 创建服务器端(Server)代码:
import java.io.*; import java.net.*; public class ChatServer { private static final int PORT = 12345; private static Socket socket; public static void main(String[] args) throws IOException { serverSocket = new ServerSocket(PORT); System.out.println("服务器启动,等待客户端连接..."); while (true) { socket = serverSocket.accept(); System.out.println("客户端已连接:" + socket.getInetAddress()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); String userInput; while ((userInput = in.readLine()) != null) { System.out.println("收到消息:" + userInput); broadcastMessage(out, userInput); } socket.close(); } } private static void broadcastMessage(PrintWriter out, String message) { for (Socket client : new ArrayList<Socket>(clients)) { if (client != socket) { try { out.println(message); } catch (IOException e) { e.printStackTrace(); clients.remove(client); try { client.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } } }
- 创建客户端(Client)代码:
import java.io.*; import java.net.*; public class ChatClient { private static final String SERVER_ADDRESS = "localhost"; private static final int PORT = 12345; private static Socket socket; private static BufferedReader in; private static PrintWriter out; public static void main(String[] args) throws IOException { socket = new Socket(SERVER_ADDRESS, PORT); System.out.println("已连接到服务器:" + SERVER_ADDRESS + ":" + PORT); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while (true) { System.out.print("请输入消息:"); userInput = stdIn.readLine(); if (userInput.equalsIgnoreCase("exit")) { break; } out.println(userInput); System.out.println("服务器回复:" + in.readLine()); } socket.close(); } }
- 分别运行服务器端和客户端代码。首先启动服务器端,然后启动一个或多个客户端。现在可以在客户端输入消息并查看服务器的回复。
注意:这个示例仅适用于单个服务器和客户端。要实现多个客户端之间的通信,可以将客户端添加到clients
列表中,并在broadcastMessage
方法中遍历该列表以向所有客户端发送消息。同时,为了简化代码,这里没有处理异常。在实际应用中,应该对异常进行适当的处理。