Java编写一个测试应用程序,作为聊天服务器(ip:192.168.1.1,端口:8888),等待来自多个客户端的连接请求,通信应该通过多线程使用TCP协议来处理连接。
时间: 2024-03-24 22:42:00 浏览: 160
以下是一个简单的Java程序,可以作为聊天服务器,等待来自多个客户端的连接请求。程序使用多线程和TCP协议来处理连接,可以同时与多个客户端进行通信。你可以将该程序保存为ChatServer.java文件,并在命令行中运行它。
```java
import java.io.*;
import java.net.*;
public class ChatServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8888)) {
System.out.println("Chat server is running on port 8888...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Accepted connection from " + clientSocket);
ClientHandler clientHandler = new ClientHandler(clientSocket);
clientHandler.start();
}
} catch (IOException e) {
System.out.println("Error starting the chat server: " + e.getMessage());
}
}
}
class ClientHandler extends Thread {
private Socket clientSocket;
private BufferedReader in;
private PrintWriter out;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println("Welcome to the chat server!");
while (true) {
String inputLine = in.readLine();
if (inputLine == null) break;
System.out.println("Received message from " + clientSocket + ": " + inputLine);
out.println("You said: " + inputLine);
}
} catch (IOException e) {
System.out.println("Error handling client: " + e.getMessage());
} finally {
try {
clientSocket.close();
} catch (IOException e) {
System.out.println("Error closing client socket: " + e.getMessage());
}
}
}
}
```
该程序会监听端口8888,等待客户端连接请求。当客户端连接时,程序会为每个客户端启动一个新的线程(ClientHandler),与客户端进行通信。
客户端可以使用以下代码连接到聊天服务器:
```java
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) {
try (Socket socket = new Socket("192.168.1.1", 8888);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
System.out.println("Connected to the chat server!");
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String inputLine = console.readLine();
if (inputLine == null || inputLine.equals("quit")) break;
out.println(inputLine);
String response = in.readLine();
System.out.println("Server response: " + response);
}
} catch (IOException e) {
System.out.println("Error connecting to the chat server: " + e.getMessage());
}
}
}
```
在命令行中运行ChatClient.java,你可以与聊天服务器进行通信。当你输入一条消息并按下回车键时,消息将被发送到服务器,并显示服务器的响应。如果你想退出聊天室,请输入“quit”。
阅读全文