用java写一个多线程聊天程序
时间: 2023-08-04 21:23:08 浏览: 97
java多线程聊天程序
下面是一个简单的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;
public class ChatServer implements Runnable {
private Socket socket;
private static final int PORT = 8080;
public ChatServer(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
writer.println("Welcome to the chat room.");
while (true) {
String message = reader.readLine();
if (message.equals("bye")) {
break;
}
System.out.println("Received message: " + message);
writer.println("You said: " + message);
}
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Chat server started on port " + PORT);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected.");
Thread thread = new Thread(new ChatServer(socket));
thread.start();
}
}
}
```
这个程序启动一个服务器,在接受到来自客户端的消息后,将消息原样返回给客户端。可以通过启动多个客户端连接到这个服务器,从而实现多人聊天功能。
阅读全文