Java通过Socket来实现简单多人聊天室源代码
时间: 2024-05-07 13:23:09 浏览: 58
java Socket实现的多人聊天 源代码
下面是一个简单的Java多人聊天室的源代码,使用Socket通信实现:
Server端代码:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
// 用来存储所有连接到服务器的客户端
private static Set<Socket> clients = new HashSet<>();
public static void main(String args[]) {
try {
// 创建一个ServerSocket,监听端口8888
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started.");
while (true) {
// 等待客户端连接
Socket client = serverSocket.accept();
clients.add(client);
System.out.println("New client connected.");
// 创建线程处理该客户端的消息
new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println("Received message: " + line);
// 将消息广播给所有客户端
for (Socket otherClient : clients) {
if (otherClient != client) {
PrintWriter out = new PrintWriter(otherClient.getOutputStream(), true);
out.println(line);
}
}
}
// 客户端关闭连接
clients.remove(client);
System.out.println("Client disconnected.");
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Client端代码:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatClient {
public static void main(String args[]) {
try {
// 连接到服务器
Socket socket = new Socket("localhost", 8888);
System.out.println("Connected to server.");
// 创建一个线程接收服务器的广播消息
new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
// 从控制台读取用户输入,并发送给服务器
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = reader.readLine()) != null) {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用方法:
1. 在命令行中运行ChatServer.java启动服务器;
2. 在多个命令行中运行ChatClient.java,连接到服务器;
3. 在任意一个客户端输入消息,服务器会将该消息广播给所有客户端。
阅读全文