在这篇文章中,我们将学习如何使用Java来实现一个简单的本地实时聊天系统。我们将使用Java的Socket编程来实现这个功能。以下是详细的步骤和代码示例。
- 创建服务器端
首先,我们需要创建一个服务器端来监听客户端的连接请求。服务器端将负责接收来自客户端的消息并将其广播给所有已连接的客户端。
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
private static final int PORT = 8080;
private static Set<PrintWriter> clientWriters = new HashSet<>();
public static void main(String[] args) throws IOException {
System.out.println("Chat Server is running on port " + PORT);
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new ClientHandler(listener.accept()).start();
}
} finally {
listener.close();
}
}
private static class ClientHandler extends Thread {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
public ClientHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
synchronized (clientWriters) {
clientWriters.add(out);
}
String message;
while ((message = in.readLine()) != null) {
System.out.println("Received message: " + message);
synchronized (clientWriters) {
for (PrintWriter writer : clientWriters) {
writer.println(message);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
synchronized (clientWriters) {
clientWriters.remove(out);
}
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 创建客户端
接下来,我们需要创建一个客户端来连接到服务器并发送/接收消息。客户端将通过控制台输入消息并发送给服务器,同时接收来自服务器的消息并显示在控制台上。
import java.io.*;
import java.net.*;
public class ChatClient {
private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 8080;
public static void main(String[] args) throws IOException {
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
Thread receiveThread = new Thread(() -> {
try {
String message;
while ((message = in.readLine()) != null) {
System.out.println("Server: " + message);
}
} catch (IOException e) {
e.printStackTrace();
}
});
receiveThread.start();
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
}
socket.close();
}
}
- 运行程序
现在我们已经准备好了服务器和客户端的代码,我们可以分别运行它们来实现本地实时聊天功能。首先启动服务器,然后启动一个或多个客户端。在客户端的控制台中输入消息,其他客户端应该能够看到这些消息。