NIO群聊系统demo示例

NIO群聊系统demo示例

基本框架:

image-20241203084205278

一、服务端

服务端代码

package nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;


public class MyServer {
   
   

    //定义属性
    private Selector selector;
        //做监听的
    private ServerSocketChannel listenChannel;
    public static final int Port = 6667;


    //构造器
    //初始化
    public MyServer(){
   
   

        try{
   
   
            //得到选择器
            selector = Selector.open();
            //
            listenChannel = ServerSocketChannel.open();
            //bind port
            listenChannel.socket().bind(new InetSocketAddress(Port));
            //set 非阻塞
            listenChannel.configureBlocking(false);
            //将listener注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch(IOException e){
   
   
            e.printStackTrace();
        }
    }

    public void listen(){
   
   

        try {
   
   
            //循环
            while(true){
   
   
                int count = selector.select(2000);
                if(count>0){
   
   //event come
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
   
   
                        //取出selectorkey
                        SelectionKey key = iterator.next();

                        //listened accept
                        if(key.isAcceptable()){
   
   

                            SocketChannel socketChannel = listenChannel.accept();
                            //将该sc注册到select上面
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector,SelectionKey.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值