實現一個Java聊天室,你可以使用套接字編程(Socket Programming)和多線程。以下是一個簡單的Java聊天室實現步驟:
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
private static final int PORT = 12345;
private static List<Socket> clients = new ArrayList<>();
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server started, waiting for connections...");
while (true) {
Socket clientSocket = serverSocket.accept();
clients.add(clientSocket);
System.out.println("New client connected: " + clientSocket.getInetAddress());
new Thread(new ClientHandler(clientSocket)).start();
}
}
}
import java.io.*;
import java.net.*;
public class Client {
private static final String SERVER_ADDRESS = "localhost";
private static final int PORT = 12345;
public static void main(String[] args) throws IOException {
Socket socket = new Socket(SERVER_ADDRESS, PORT);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
new Thread(() -> {
try {
while (true) {
String message = userInput.readLine();
if (message != null && !message.isEmpty() && message.equalsIgnoreCase("/exit")) {
break;
}
output.println(message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
while (true) {
String message = input.readLine();
if (message != null && !message.isEmpty() && message.equalsIgnoreCase("/exit")) {
break;
}
System.out.println("Received from server: " + message);
}
}
}
首先運行Server
類,然后運行多個Client
類實例。現在你可以在不同的客戶端輸入消息并查看它們是否在其他客戶端上顯示。
注意:這個示例僅適用于單個服務器和多個客戶端。如果你需要實現一個具有多個服務器和服務器之間的通信的聊天室,你需要使用更復雜的網絡編程技術,例如分布式系統。