java聊天室 多人代码
时间: 2023-07-30 07:08:36 浏览: 100
下面是一个简单的Java多人聊天室的示例代码:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
private static final int PORT = 8080;
private static Set<PrintWriter> clients = new HashSet<>();
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Chat Server started on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected");
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
clients.add(writer);
Thread clientThread = new Thread(new ClientHandler(clientSocket, writer));
clientThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void broadcastMessage(String message, PrintWriter sender) {
for (PrintWriter client : clients) {
if (client != sender) {
client.println(message);
}
}
}
}
class ClientHandler implements Runnable {
private Socket clientSocket;
private PrintWriter writer;
public ClientHandler(Socket socket, PrintWriter writer) {
this.clientSocket = socket;
this.writer = writer;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
String incomingMessage;
while ((incomingMessage = reader.readLine()) != null) {
System.out.println("Received message: " + incomingMessage);
ChatServer.broadcastMessage(incomingMessage, writer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
ChatServer.clients.remove(writer);
}
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
这是一个简单的基于TCP的多人聊天室服务器。它监听8080端口,并在有新客户端连接时创建一个新的线程来处理客户端的消息。
客户端可以使用任何TCP Socket客户端来连接到服务器,并发送消息。服务器接收到消息后,会将消息广播给所有连接的客户端(除了发送者自己)。
请注意,这只是一个基本示例,没有处理异常情况、用户认证、消息格式化等。在实际开发中,您可能需要根据自己的需求进行适当的修改和扩展。
阅读全文