java高级群聊聊天室
时间: 2023-12-22 19:29:09 浏览: 105
Java群聊天室
以下是Java高级群聊聊天室的代码示例:
1. 服务器端代码:
```java
package com.xiaoxuzhu;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ServerOneToManyServerFrame {
private static final int PORT = 8888;
private static List<ServerThread> clients = new ArrayList<>();
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("服务器已启动,待客户端连接...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("客户端连接成功:" + clientSocket);
ServerThread serverThread = new ServerThread(clientSocket, clients);
clients.add(serverThread);
serverThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 客户端代码:
```java
package com.xiaoxuzhu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ClientOneToManyClientFrame {
private static final String SERVER_IP = "127.0.0.1";
private static final int SERVER_PORT = 8888;
public static void main(String[] args) {
try {
Socket socket = new Socket(SERVER_IP, SERVER_PORT);
System.out.println("成功连接到服务器:" + socket);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
// 启动接收消息的线程
new Thread(new ClientThread(reader)).start();
// 发送消息
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
String message;
while ((message = consoleReader.readLine()) != null) {
writer.println(message);
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static class ClientThread implements Runnable {
private BufferedReader reader;
public ClientThread(BufferedReader reader) {
this.reader = reader;
}
@Override
public void run() {
try {
String message;
while ((message = reader.readLine()) != null) {
System.out.println("收到消息:" + message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
阅读全文