要實現一個簡易的聊天室,可以使用Socket編程來實現客戶端和服務端之間的通信。以下是一個簡單的Java聊天室的實現步驟:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ChatServer {
private static List<PrintWriter> clients = new ArrayList<>();
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server started...");
while (true) {
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
clients.add(out);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void broadcast(String message) {
for (PrintWriter client : clients) {
client.println(message);
}
}
private static class ClientHandler implements Runnable {
private Socket clientSocket;
private Scanner in;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
try {
in = new Scanner(clientSocket.getInputStream());
while (in.hasNextLine()) {
String message = in.nextLine();
broadcast(message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
clients.remove(new PrintWriter(clientSocket.getOutputStream()));
}
}
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 8080);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner in = new Scanner(socket.getInputStream());
Scanner scanner = new Scanner(System.in)) {
System.out.println("Connected to server. Start typing messages:");
Thread t = new Thread(() -> {
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
});
t.start();
while (true) {
String message = scanner.nextLine();
out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
這樣就可以實現一個簡單的聊天室,Server端負責接受客戶端連接并廣播消息,Client端負責發送和接收消息。可以通過運行多個Client端來進行聊天。