使用NIO实现非阻塞式网络编程

  • 服务端
/**
 * @description:
 * @author: yrm
 * @create: 2020-08-16 20:07
 **/
public class NIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel listener = null;
        System.out.println("服务器已启动...");
        try {
            //创建服务器通道
            listener = ServerSocketChannel.open();
            //绑定端口号
            listener.bind(new InetSocketAddress("10.9.63.249",5555));
            //设置非阻塞
            listener.configureBlocking(false);
            //创建selector选择器
            Selector selector = Selector.open();
            //将通道注册到选择器上,并设置事件
            listener.register(selector, SelectionKey.OP_ACCEPT);
            //监听有没有事件发生(轮询法,没有事件发生阻塞)
            while (selector.select() > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                while (it.hasNext()) {
                    SelectionKey selectionKey = it.next();
                    //判断selectKey
                    if (selectionKey.isAcceptable()) {
                        //表示有客户端请求,接受请求
                        SocketChannel socketChannel = listener.accept();
                        System.out.println(socketChannel.getRemoteAddress()+"进入了聊天室");
                        //设置非阻塞
                        socketChannel.configureBlocking(false);
                        //将监听到的通道注册到选择器上
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    }else if (selectionKey.isReadable()) {
                        SocketChannel sChannel = (SocketChannel) selectionKey.channel();
                        //创建缓冲区
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int len = 0;
                        try {
                            while ((len = sChannel.read(buffer)) > 0) {
                                //每进行读取则flip一次
                                buffer.flip();
                                System.out.println(sChannel.getRemoteAddress() +"说了:"+new String(buffer.array(), 0, buffer.limit()));
                                buffer.clear();
                            }
                            if (len == -1) {
                                sChannel.close();
                            }
                        } catch (IOException e) {
                            System.out.println(sChannel.getRemoteAddress()+"异常退出了!");
                            sChannel.close();
                        }
                    }
                }
                it.remove();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            listener.close();
        }

    }
}
  • 客户端
/**
 * @description:
 * @author: yrm
 * @create: 2020-08-16 13:55
 * 使用NIO实现非阻塞式网络编程
 **/
public class NIOClient {
    public static void main(String[] args) throws Exception {
        //创建socket通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("10.9.63.249", 5555));
        //给通道设置非阻塞
        socketChannel.configureBlocking(false);
        Scanner scanner = new Scanner(System.in);
        while (true) {
            //创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            String data = scanner.nextLine();
            //将数据放入到缓冲区中
            buffer.put(data.getBytes());
            buffer.flip();
            //将缓冲区中的数据写入到通道中
            socketChannel.write(buffer);
            buffer.clear();
            if (data.equals("886")) {
                break;
            }
        }
        socketChannel.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值