java 模拟多人聊天室,服务器与客户机

java 复制代码
package p1008;
import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
    private static final int PORT = 12345;
    private static Set<ClientHandler> clientHandlers = new HashSet<>();

    public static void main(String[] args) {
        System.out.println("聊天服务器启动...");

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            while (true) {
                new ClientHandler(serverSocket.accept()).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class ClientHandler extends Thread {
        private Socket socket;
        private PrintWriter out;
        private BufferedReader in;

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

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

                synchronized (clientHandlers) {
                    clientHandlers.add(this);
                }

                // 发送欢迎消息
                out.println("欢迎来到聊天室!");
                System.out.println(socket.getLocalAddress()+" 来到了聊天室~!");



                synchronized (clientHandlers) {
                    for (ClientHandler client : clientHandlers) {
                        if (client != this) { // 排除发送者
                            client.out.println(socket.getLocalAddress()+" 来到了聊天室~!");
                        }
                    }
                }


                String message;
                while ((message = in.readLine()) != null) {
                    System.out.println("收到消息: " + message);
                    // 广播消息给所有在线用户,排除发送者
                    synchronized (clientHandlers) {
                        for (ClientHandler client : clientHandlers) {
                            if (client != this) { // 排除发送者
                                client.out.println(message);
                            }else{
                                client.out.println("自己说:"+message);
                            }
                        }
                    }
                    if(message.equals("quit")){
                        System.out.println(socket.getLocalAddress()+" 退出服务器");
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                synchronized (clientHandlers) {
                    clientHandlers.remove(this);
                }
            }
        }
    }
}
java 复制代码
package p1008;

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

public class ChatClient {
    private static final String SERVER_ADDRESS = "localhost"; // 服务器地址
    private static final int PORT = 12345;

    public static void main(String[] args) {
        try (Socket socket = new Socket(SERVER_ADDRESS, PORT);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {

            // 接收服务器消息的线程
            new Thread(() -> {
                String response;
                try {
                    while ((response = in.readLine()) != null) {
                        System.out.println(response);
                    }
                } catch (IOException e) {
                    System.out.println("结束与服务器通讯~!");
                    //e.printStackTrace();
                }
            }).start();

            // 发送消息到服务器
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                if(userInput.equals("quit"))
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("结束");
    }
}
相关推荐
穿林鸟5 分钟前
Spring Boot项目信创国产化适配指南
java·spring boot·后端
褚翾澜6 分钟前
Haskell语言的NoSQL
开发语言·后端·golang
zh_xuan18 分钟前
LeeCode 57. 插入区间
c语言·开发语言·数据结构·算法
2401_8534482323 分钟前
C嘎嘎类里面的额函数
c语言·开发语言·c++
此木|西贝24 分钟前
【设计模式】模板方法模式
java·设计模式·模板方法模式
巷北夜未央33 分钟前
数据结构之二叉树Python版
开发语言·数据结构·python
wapicn9934 分钟前
手机归属地查询Api接口,数据准确可靠
java·python·智能手机·php
旧识君1 小时前
移动端1px终极解决方案:Sass混合宏工程化实践
开发语言·前端·javascript·前端框架·less·sass·scss
hycccccch1 小时前
Springcache+xxljob实现定时刷新缓存
java·后端·spring·缓存
郝YH是人间理想1 小时前
OpenCV基础——傅里叶变换、角点检测
开发语言·图像处理·人工智能·python·opencv·计算机视觉