手撸一个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等库。

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

相关推荐
Codebee6 小时前
实战AI增强注解驱动:OneCode语义工程的智能升级
架构
ai小鬼头9 天前
AIStarter开发者熊哥分享|低成本部署AI项目的实战经验
后端·算法·架构
美狐美颜sdk9 天前
如何在直播SDK中实现高性能面具贴纸渲染?底层架构与优化方案详解
架构
19899 天前
【Dify精讲】第19章:开源贡献指南
运维·人工智能·python·架构·flask·开源·devops
HsuYang10 天前
我是这样使用AI提高前端基础建设工具效率的
前端·架构·node.js
Wgllss10 天前
Kotlin+协程+FLow+Channel+Compose 实现一个直播多个弹幕效果
android·架构·android jetpack
天天摸鱼的java工程师10 天前
如何设计一个社交平台的关注/粉丝系统?一位8年Java开发者的架构心路
java·后端·架构
安科瑞刘鸿鹏10 天前
ABAT100助力光储电站电池“可视化”管理
大数据·运维·网络·数据库·物联网·安全·架构
程序员Better10 天前
玄戒O1芯片架构大揭秘:0核异构设计如何重构移动端开发范式?
人工智能·机器学习·架构
前端付豪10 天前
🧠「我让 Assistant 像人一样聊天」:Google Assistant 对话系统技术架构全解密!
前端·后端·架构