java如何实现群聊,用Java控制台实现简单的群聊天室
时间: 2024-02-25 08:51:54 浏览: 90
JavaClient&Server.rar_java 群聊_java 聊天室_java聊天室_群聊_聊天
Java实现群聊的方法有很多种,其中一种比较简单的方法是使用Java Socket编程实现。
以下是一个简单的Java控制台群聊天室的代码:
1. 服务端代码
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
private static List<Socket> sockets = new ArrayList<>();
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = server.accept();
sockets.add(socket);
System.out.println("客户端已连接,当前连接数:" + sockets.size());
new ServerThread(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ServerThread extends Thread {
private Socket socket;
private BufferedReader reader;
public ServerThread(Socket socket) {
this.socket = socket;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
String line;
try {
while ((line = reader.readLine()) != null) {
System.out.println("客户端消息:" + line);
for (Socket socket : sockets) {
if (socket != this.socket) {
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(line);
writer.flush();
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
sockets.remove(socket);
System.out.println("客户端已断开连接,当前连接数:" + sockets.size());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
2. 客户端代码
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
new ClientThread(socket).start();
String line;
while ((line = reader.readLine()) != null) {
writer.println(line);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ClientThread extends Thread {
private Socket socket;
private BufferedReader reader;
public ClientThread(Socket socket) {
this.socket = socket;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
String line;
try {
while ((line = reader.readLine()) != null) {
System.out.println("收到消息:" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
以上代码实现了一个简单的Java控制台群聊天室,服务端启动后等待客户端连接,客户端连接后可以发送消息,服务端接收到消息后将其转发给所有连接的客户端。
阅读全文