在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端口,当客户端连接时,服务器将接收到的消息广播给所有连接的客户端。客户端可以发送消息给服务器,然后服务器将消息广播给其他客户端。
请注意,这个示例仅用于演示目的,实际应用中可能需要考虑更多的功能和优化,例如多个频道、用户身份验证等。