用java代码写一个在线聊天室
时间: 2023-09-02 18:13:07 浏览: 93
好的,以下是一个简单的在线聊天室的 Java 代码实现,包括服务器端和客户端部分的代码。请注意,这只是一个简单的示例,您可以根据具体需求进行修改和完善。
服务器端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ChatServer {
private ArrayList<PrintWriter> clients;
public static void main(String[] args) {
ChatServer server = new ChatServer();
server.start();
}
public ChatServer() {
clients = new ArrayList<>();
}
public void start() {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("客户端 " + clientSocket.getInetAddress().getHostAddress() + " 已连接");
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clients.add(writer);
Thread thread = new Thread(new ClientHandler(clientSocket));
thread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class ClientHandler implements Runnable {
private Socket clientSocket;
private BufferedReader reader;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("接收到消息:" + message);
broadcast(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void broadcast(String message) {
for (PrintWriter writer : clients) {
writer.println(message);
writer.flush();
}
}
}
}
```
客户端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ChatClient {
private BufferedReader reader;
private PrintWriter writer;
public static void main(String[] args) {
ChatClient client = new ChatClient();
client.start();
}
public void start() {
try {
Socket socket = new Socket("localhost", 8888);
System.out.println("已连接到服务器");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream());
Thread thread = new Thread(new ServerHandler());
thread.start();
String message;
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
while ((message = console.readLine()) != null) {
writer.println(message);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class ServerHandler implements Runnable {
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("收到消息:" + message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
请注意,以上代码仅供参考,您需要根据实际情况进行修改和完善。
阅读全文