在Java中搭建一個簡單的聊天室,你可以使用套接字編程(Socket Programming)和多線程。以下是一個基本的聊天室實現步驟:
import java.io.*;
import java.net.*;
public class ChatServer {
private int port;
private ServerSocket serverSocket;
private Socket socket;
public ChatServer(int port) throws IOException {
this.port = port;
serverSocket = new ServerSocket(port);
}
public void start() throws IOException {
System.out.println("服務器啟動,等待客戶端連接...");
socket = serverSocket.accept();
System.out.println("客戶端已連接:" + socket.getInetAddress());
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("收到消息:" + message);
broadcast(message, socket);
}
}
private void broadcast(String message, Socket sender) {
for (Socket client : clients) {
if (client != sender) {
try {
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
out.println(message);
} catch (IOException e) {
e.printStackTrace();
client.close();
removeClient(client);
}
}
}
}
private void removeClient(Socket client) {
clients.remove(client);
}
public static void main(String[] args) {
int port = 12345;
ChatServer server;
try {
server = new ChatServer(port);
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
public class ChatClient {
private String serverAddress;
private int port;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ChatClient(String serverAddress, int port) throws IOException {
this.serverAddress = serverAddress;
this.port = port;
socket = new Socket(serverAddress, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}
public void sendMessage(String message) {
out.println(message);
}
public void receiveMessage() {
try {
String message = in.readLine();
System.out.println("收到消息:" + message);
} catch (IOException e) {
e.printStackTrace();
removeClient();
}
}
public void removeClient() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String serverAddress = "localhost";
int port = 12345;
ChatClient client;
try {
client = new ChatClient(serverAddress, port);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String message;
while ((message = in.readLine()) != null) {
client.sendMessage(message);
client.receiveMessage();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
首先運行ChatServer
類,然后運行ChatClient
類。現在你可以嘗試在客戶端發送消息,服務器端會收到并廣播給所有連接的客戶端。
注意:這個示例僅適用于一個簡單的聊天室,沒有實現用戶身份驗證、私聊功能等高級功能。你可以根據自己的需求對代碼進行修改和擴展。