java如何实现一个简易的聊天室

avatar
作者
筋斗云
阅读量:0

要实现一个简易的聊天室,可以使用Socket编程来实现客户端和服务端之间的通信。以下是一个简单的Java聊天室的实现步骤:

  1. 创建一个Server端:
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()));             }         }     } } 
  1. 创建一个Client端:
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端来进行聊天。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!