java简单NIO示例

服务端

// 得到serverSocketChannel对象并设置为非阻塞
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
// 得到一个selector对象用于监控
Selector selector = Selector.open();
// 注册到selector
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// 绑定端口号
serverSocketChannel.bind(new InetSocketAddress(10000));
while (true) {
    // 监控客户端-NIO非阻塞
    if (selector.select(2000) == 0) {
        System.out.println("没有客户端连接,服务端也可以干其它事情");
        continue;
    }
    // 拿到selectedKeys,进行处理
    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
    while (iterator.hasNext()) {
        SelectionKey selectionKey = iterator.next();
        if (selectionKey.isAcceptable()) {
            System.out.println("客户端连接请求事件");
            SocketChannel channel = serverSocketChannel.accept();
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
        }
        if (selectionKey.isReadable()) {
            System.out.println("读取客户端数据事件");
            SocketChannel channel = (SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
            channel.read(byteBuffer);
            System.out.println("接收客户端数据:" + new String(byteBuffer.array()));
        }
        // 移除当前selectionKey,防止重复处理
        iterator.remove();
    }
}

 

客户端

// 开启一个网络通道并设置为非阻塞的方式
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
// 服务端的IP地址和端口号
InetSocketAddress address = new InetSocketAddress("localhost", 10000);
// 连接服务器-NIO非阻塞
if (!socketChannel.connect(address)) {
    while (!socketChannel.finishConnect()) {
        System.out.println("客户端:可以执行一些代码");
    }
}
// 得到一个缓冲区并存入数据
ByteBuffer byteBuffer = ByteBuffer.wrap("abc".getBytes());
// 发送数据
socketChannel.write(byteBuffer);
// 保持客户端程序不退出,保持连接状态
System.in.read();

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值