第三章 第二节NIO网络编程应用实例-群聊系统

1. 案例需求

编写一个 NIO 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
实现多人群聊
服务器端:可以监测用户上线,离线,并实现消息转发功能
客户端:通过channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发得到)
目的:进一步理解NIO非阻塞网络编程机制
在这里插入图片描述
在这里插入图片描述

2. 流程

服务端

  1. 监听客户端连接
  • 初始化工作,实例化selector,实例化serverSocketChannel.设置非阻塞。注册ACCEPT事件
  • 监听客户端连接请求,将socketChannel注册到selector,注册为READ事件。
  1. 读取客户端信息,打印输出
  • 读取socketChannel信息
  1. 将客户端信息转发到其他的客户端
  • 获取所有的keys。如果channel instanceof socketChannel && 不是当前的客户端的channel,向其他客户端channel写入数据。

客户端

  1. 发送信息
    初始化工作,实例化selector,实例化SocketChannel,连接服务器.设置非阻塞。向socketChannel写入信息
  2. 接受信息
    selector.select()看是否有事件,有则遍历key,获取通道读取数据。
    注意:读写数据都是通过channel。
    三种方法获取channel:
  3. serverSocketChannel.accept() 服务端
  4. socketChannel.open(new InetSocketAddress(“127.0.0.1”, PORT)); 客户端
  5. SocketChannel sc = (SocketChannel) key.channel(); 通过selector的selectionKey获取(事件获取)

3. 代码

服务端

public class GroupChatServer {
   
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;
    //构造器
    //初始化工作
    public GroupChatServer() {
   
        try {
   
            //得到选择器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel =  ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //将该listenChannel 注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e) {
   
            e.printStackTrace();
        }
    }
    //监听
    public void listen() {
   
        System.out.println("监听线程: " + Thread.currentThread().getName());
        try {
   
            //循环处理
            while (true) {
   
                int count = selector.select();
                if(count > 0) {
   //有事件处理
                    //遍历得到selectionKey 集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
   
                        //取出selectionkey
                        SelectionKey key = iterator.next();
                        //监听到accept
                        if(key.isAcceptable()) {
   
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            //将该 sc 注册到seletor
                            sc.register(selector, SelectionKey.OP_READ);
                            //提示
                            System.out.println(sc.getRemoteAddress() + " 上线 ");
                        }
                        if(key.isReadable()) {
    //通道发送read事件,即通道是可读的状态
                            //处理读 (专门写方法..)
                            readData(key);
                        }
                        //当前的key 删除,防止重复处理
                        iterator.remove();
                    }

                } else {
   
                    System.out.println("等待....");
                }
            }
        }catch (Exception e) {
   
            e.printStackTrace();
        }finally {
   
            //发生异常处理....
        }
    }

    //读取客户端消息
    private void readData(SelectionKey key) {
   
        //取到关联的channle
        SocketChannel channel = null;
        try {
   
           //得到channel
            channel = (SocketChannel) key.channel();
            //创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            //根据count的值做处理
            if(count > 0) {
   
                //把缓存区的数据转成字符串
                String msg = new String(buffer.array());
                //输出该消息
                System.out.println("form 客户端: " + msg);

                //向其它的客户端转发消息(去掉自己), 专门写一个方法来处理
                sendInfoToOtherClients(msg, channel);
            }
        }catch (IOException e) {
   
            try {
   
                System.out.println(channel.getRemoteAddress() + " 离线了..");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            }catch (IOException e2) {
   
                e2.printStackTrace();;
            }
        }
    }
    //转发消息给其它客户(通道)
    private void sendInfoToOtherClients(String msg, SocketChannel self ) throws  IOException{
   
        System.out.println("服务器转发消息中...");
        System.out.println("服务器转发数据给客户端线程: " + Thread.currentThread().getName());
        //遍历 所有注册到selector 上的 SocketChannel,并排除 self
        for(SelectionKey key: selector.keys()) {
   
            //通过 key  取出对应的 SocketChannel
            Channel targetChannel = key.channel();
            //排除自己
            if(targetChannel instanceof  SocketChannel && targetChannel != self) {
   
                //转型
                SocketChannel dest = (SocketChannel)targetChannel;
                //将msg 存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                //将buffer 的数据写入 通道
                dest.write(buffer);
            }
        }

    }
    public static void main(String[] args) {
   
        //创建服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}

客户端


public class GroupChatClient {
   

    //定义相关的属性
    private final String HOST = "127.0.0.1"; // 服务器的ip
    private final int PORT = 6667; //服务器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;
    //构造器, 完成初始化工作
    public GroupChatClient() throws IOException {
   
        selector = Selector.open();
        //连接服务器
        socketChannel = socketChannel.open(new InetSocketAddress("127.0.0.1", PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //将channel 注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        //得到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok...");
    }

    //向服务器发送消息
    public void sendInfo(String info) {
   
        info = username + " 说:" + info;
        try {
   
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e) {
   
            e.printStackTrace();
        }
    }
    //读取从服务器端回复的消息
    public void readInfo() {
   
        try {
   
            int readChannels = selector.select();
            if(readChannels > 0) {
   //有可以用的通道
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
   
                    SelectionKey key = iterator.next();
                    if(key.isReadable()) {
   
                        //得到相关的通道
                       SocketChannel sc = (SocketChannel) key.channel();
                       //得到一个Buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //读取
                        sc.read(buffer);
                        //把读到的缓冲区的数据转成字符串
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iterator.remove(); //删除当前的selectionKey, 防止重复操作
            } else {
   
                //System.out.println("没有可以用的通道...");
            }

        }catch (Exception e) {
   
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
   
        //启动我们客户端
        GroupChatClient chatClient = new GroupChatClient();
        //启动一个线程, 每隔3秒,读取从服务器发送数据。这里启动线程是因为主线程要发送数据接受用户数据,会阻塞,因此要用新的线程处理接受消息。
        new Thread() {
   
            public void run() {
   
                while (true) {
   
                    chatClient.readInfo();
                    try {
   
                        Thread.currentThread().sleep(3000);
                    }catch (InterruptedException e) {
   
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        //发送数据给服务器端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
   
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }
}

最近更新

  1. TCP协议是安全的吗?

    2023-12-18 02:56:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-18 02:56:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-18 02:56:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-18 02:56:01       20 阅读

热门阅读

  1. arcgis图层样式应用geoserver问题

    2023-12-18 02:56:01       46 阅读
  2. unknown error 1146

    2023-12-18 02:56:01       39 阅读
  3. Mysql(事务)

    2023-12-18 02:56:01       53 阅读
  4. 什么是容器编排?

    2023-12-18 02:56:01       48 阅读
  5. 【无标题】

    2023-12-18 02:56:01       42 阅读
  6. 【前端学习记录】Vuex状态管理学习笔记

    2023-12-18 02:56:01       43 阅读
  7. LeetCode27.移除数组元素

    2023-12-18 02:56:01       49 阅读
  8. 骑砍战团MOD开发(19)-ID掩码算法

    2023-12-18 02:56:01       38 阅读
  9. Ubuntu20.04 配置NTP服务器

    2023-12-18 02:56:01       35 阅读