手撸一个java简易聊天室

创建一个Java聊天室涉及到网络编程、多线程处理以及用户界面设计。这里我将提供一个简单的Java聊天室实现,包括服务器端和客户端的基本逻辑。

服务器端

服务器端负责接收客户端的消息,并将其广播给所有连接的客户端。

java

复制

import java.io.;
import java.net.
;

import java.util.*;

public class ChatServer {

private static final int PORT = 6789;

private static List clients = Collections.synchronizedList(new ArrayList<>());

复制代码
public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = new ServerSocket(PORT);
    System.out.println("Chat server started on port " + PORT);

    while (true) {
        try (Socket clientSocket = serverSocket.accept()) {
            System.out.println("New client connected: " + clientSocket.getRemoteSocketAddress());
            ClientHandler clientHandler = new ClientHandler(clientSocket);
            clients.add(clientHandler);
            clientHandler.start();
        }
    }
}

public static void broadcastMessage(String message) {
    for (ClientHandler client : clients) {
        client.sendMessage(message);
    }
}

private static class ClientHandler extends Thread {
    private Socket clientSocket;
    private PrintWriter out;

    public ClientHandler(Socket socket) {
        this.clientSocket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out = new PrintWriter(clientSocket.getOutputStream(), true);

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                broadcastMessage(inputLine);
            }
        } catch (IOException e) {
            System.out.println("Error in client handler: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            clients.remove(this);
        }
    }

    public void sendMessage(String message) {
        out.println(message);
    }
}

}

客户端

客户端负责连接服务器,发送消息,并接收服务器广播的消息。

java

复制

import java.io.;
import java.net.
;

import java.util.Scanner;

public class ChatClient {

private static final String HOST = "localhost";

private static final int PORT = 6789;

复制代码
public static void main(String[] args) throws IOException {
    try (Socket socket = new Socket(HOST, PORT);
         PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
         BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         Scanner scanner = new Scanner(System.in)) {

        System.out.println("Connected to the chat server");

        // Receive messages from the server
        new Thread(() -> {
            try {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println(inputLine);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        // Send messages to the server
        while (scanner.hasNextLine()) {
            String userMessage = scanner.nextLine();
            out.println(userMessage);
        }
    }
}

}

运行说明

首先运行 ChatServer 类,它将启动服务器并等待客户端连接。

然后运行一个或多个 ChatClient 实例,它们将连接到服务器并允许用户输入消息。

用户在客户端输入的消息将被发送到服务器,服务器将广播给所有连接的客户端。

注意事项

这个聊天室实现是多线程的,每个客户端连接都会创建一个新的线程。

客户端和服务器之间的通信使用TCP协议。

这个实现是基本的,没有考虑异常处理、断线重连、用户身份验证等高级特性。

为了更好的用户体验,你可以考虑添加图形用户界面(GUI),使用Swing或JavaFX等库。

这个聊天室是一个基础的示例,可以根据你的需要进行扩展和改进。

相关推荐
海宇服务3 小时前
零信任架构实战:基于海宇全能小微企业报告构建自动化园区商户免押租赁资信核验网关
大数据·人工智能·架构·自动化
zhangfeng11334 小时前
6篇RAG核心论文的工程启示:Vector + Graph + Agent路由混合架构实战
人工智能·架构·llm·agent
Decay__5 小时前
09_MySQL 闪回与时间点恢复 —— binlog 回放、mysqlbinlog、PITR 与误删恢复
运维·数据库·sql·mysql·架构
代码方舟6 小时前
零信任架构实战:基于天远企业法人四要素高级版构建自动化电子印章授权与签约准入网关
人工智能·架构·自动化·区块链
DevMemo8 小时前
2026 AI外呼系统技术选型:全链路延迟预算与集成成本实测,10个品牌的架构真相
人工智能·架构
EnCi Zheng9 小时前
Agent 架构怎么选:从单 Agent 到多 Agent 编排的选型决策指南
架构
阿狸猿10 小时前
事件驱动架构(EDA)的设计与应用
架构
硅基手札11 小时前
CAN 技术系列 08 · CAN 控制器寄存器与 IP 架构
驱动开发·架构·嵌入式开发·通信协议·can总线
微三云 - 廖会灵 (私域系统开发)11 小时前
企业级 SaaS 系统架构设计:单体、微服务还是模块化单体?技术选型实战
微服务·架构·系统架构