在Java中實現網絡聊天室,你可以使用套接字編程(Socket Programming)
import java.io.*;
import java.net.*;
public class ChatServer {
public static void main(String[] args) throws IOException {
int port = 12345;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String message;
while ((message = in.readLine()) != null) {
System.out.println("Received: " + message);
broadcastMessage(out, message);
}
socket.close();
System.out.println("Client disconnected");
}
}
private static void broadcastMessage(PrintWriter out, String message) {
for (Socket socket : clients) {
if (socket != null && !socket.isClosed()) {
out.println(message);
}
}
}
private static List<Socket> clients = new ArrayList<>();
}
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) throws IOException {
String serverAddress = "localhost";
int port = 12345;
Socket socket = new Socket(serverAddress, port);
System.out.println("Connected to server");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while (true) {
System.out.println("Enter your message: ");
userInput = stdIn.readLine();
if (userInput != null && !userInput.isEmpty()) {
out.println(userInput);
broadcastMessage(in, userInput + " (" + socket.getInetAddress() + ")");
}
}
}
private static void broadcastMessage(BufferedReader in, String message) throws IOException {
for (Socket socket : clients) {
if (socket != null && !socket.isClosed()) {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
}
}
}
}
這個示例中,服務器端監聽12345端口,當客戶端連接時,服務器將接收到的消息廣播給所有連接的客戶端。客戶端可以發送消息給服務器,然后服務器將消息廣播給其他客戶端。
請注意,這個示例僅用于演示目的,實際應用中可能需要考慮更多的功能和優化,例如多個頻道、用戶身份驗證等。