• NIO 实现群聊系统


    服务器

    package chat;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.*;
    import java.util.Iterator;
    
    /**
     * @author: zh
     * @create: 2023-09-13 10:52
     */
    public class Server {
    
        private Selector selector;
        private ServerSocketChannel serverSocketChannel;
        private static final int PORT = 666;
    
        public Server() throws IOException {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        }
    
        public void listen() throws IOException {
            while (true) {
                int count = selector.select();
                if (count > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        if (key.isAcceptable()) {
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + " up");
                        } else if (key.isReadable()) {
                            read(key);
                        }
                        iterator.remove();
                    }
                }
            }
        }
    
        private void read(SelectionKey key) throws IOException {
            SocketChannel socketChannel = null;
            try {
                socketChannel = (SocketChannel) key.channel();
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                int count = socketChannel.read(buffer);
                if (count > 0) {
                    String msg = new String(buffer.array());
                    System.out.println(msg);
                    send(msg, socketChannel);
                }
            } catch (Exception e) {
                System.out.println(socketChannel.getRemoteAddress() + " down");
                key.channel();
                socketChannel.close();
            }
        }
    
        private void send(String msg, SocketChannel self) throws IOException {
            System.out.println("send...");
            for (SelectionKey key : selector.keys()) {
                Channel channel = key.channel();
                if (channel instanceof SocketChannel && channel != self) {
                    SocketChannel target = (SocketChannel) channel;
                    ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
                    target.write(byteBuffer);
                }
            }
        }
    
        public static void main(String[] args) throws IOException {
            new Server().listen();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82

    客户端

    package chat;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.*;
    import java.util.Iterator;
    import java.util.Scanner;
    
    /**
     * @author: zh
     * @create: 2023-09-13 11:25
     */
    public class Client {
        private static final int PORT = 666;
        private static final String HOST = "127.0.0.1";
        private SocketChannel socketChannel;
        private Selector selector;
        private String username;
    
        public Client() throws IOException {
            selector = Selector.open();
            socketChannel = socketChannel.open(new InetSocketAddress(HOST, PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println("ready");
        }
    
        private void send(String info) throws IOException {
            info = username + " say " + info;
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }
    
        private void read() throws IOException {
            int count = selector.select();
            if (count > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        channel.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg);
                    }
                }
            }
        }
    
        public static void main(String[] args) throws IOException {
            Client client = new Client();
            new Thread(() -> {
                while (true) {
                    try {
                        client.read();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
    
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String msg = scanner.nextLine();
                client.send(msg);
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
  • 相关阅读:
    【PyTorch深度学习项目实战100例】—— 基于ShuffleNet实现中草药识别任务 | 第32例
    计算机毕业设计 SSM+Vue网上质询问诊平台系统 医疗问诊管理系统 网上预约医疗问诊系统Java Vue MySQL数据库 远程调试 代码讲解
    Linux性能分析——TOP命令详解
    第十五章 配置工作队列管理器类别
    第九章 将对象映射到 XML - 控制集合属性的映射形式
    Python教学案例 - 三天打渔、两天晒网
    守护进程(初学者必备)
    【JVM学习03】类加载与字节码技术
    《RCLane:Relay Chain Prediction for Lane Detection》论文笔记
    基于MATLAB的单目摄像机标定
  • 原文地址:https://blog.csdn.net/sanmao123456_/article/details/132852688