要用Java編寫一個簡單的聊天室,你可以使用套接字編程(Socket Programming)。這里是一個基本的聊天室實現教程:
import java.io.*;
import java.net.*;
public class ChatServer {
private static final int PORT = 12345;
private static Socket socket;
public static void main(String[] args) throws IOException {
serverSocket = new ServerSocket(PORT);
System.out.println("服務器啟動,等待客戶端連接...");
while (true) {
socket = serverSocket.accept();
System.out.println("客戶端已連接:" + socket.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String userInput;
while ((userInput = in.readLine()) != null) {
System.out.println("收到消息:" + userInput);
broadcastMessage(out, userInput);
}
socket.close();
}
}
private static void broadcastMessage(PrintWriter out, String message) {
for (Socket client : new ArrayList<Socket>(clients)) {
if (client != socket) {
try {
out.println(message);
} catch (IOException e) {
e.printStackTrace();
clients.remove(client);
try {
client.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
import java.io.*;
import java.net.*;
public class ChatClient {
private static final String SERVER_ADDRESS = "localhost";
private static final int PORT = 12345;
private static Socket socket;
private static BufferedReader in;
private static PrintWriter out;
public static void main(String[] args) throws IOException {
socket = new Socket(SERVER_ADDRESS, PORT);
System.out.println("已連接到服務器:" + SERVER_ADDRESS + ":" + PORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while (true) {
System.out.print("請輸入消息:");
userInput = stdIn.readLine();
if (userInput.equalsIgnoreCase("exit")) {
break;
}
out.println(userInput);
System.out.println("服務器回復:" + in.readLine());
}
socket.close();
}
}
注意:這個示例僅適用于單個服務器和客戶端。要實現多個客戶端之間的通信,可以將客戶端添加到clients
列表中,并在broadcastMessage
方法中遍歷該列表以向所有客戶端發送消息。同時,為了簡化代碼,這里沒有處理異常。在實際應用中,應該對異常進行適當的處理。