Linux 多路复用 I/O 对比 java NIO 网络编程

11 篇文章 0 订阅
3 篇文章 0 订阅

先介绍java NIO 网络编程比较重要的四个类

ServerSocketChannel

The ServerSocketChannel class has one purpose: to accept incoming connections. You cannot read from, write to, or connect a ServerSocketChannel. The only operation it supports is accepting a new incoming connection. The class itself only declares four methods, of which accept() is the most important. ServerSocketChannel also inherits several methods from its superclasses, mostly related to registering with a Selector for notification of incoming connections. And finally, like all channels, it has a close() method that shuts down the server socket.

SocketChannel

The SocketChannel class reads from and writes to TCP sockets. The data must be encoded in ByteBuffer objects for reading and writing. Each SocketChannel is associated with a peer Socket object that can be used for advanced configuration, but this requirement can be ignored for applications where the default options are fine.

Selector

@return The number of keys, possibly zero, whose ready-operation sets were updated
The other two select methods are blocking:
public abstract int select() throws IOException
public abstract int select(long timeout) throws IOException
The first method waits until at least one registered channel is ready to be processed before returning. The second waits no longer than timeout milliseconds for a channel to be ready before returning 0. These methods are useful if your program doesn’t have anything to do when no channels are ready to be processed.

SelectionKey

SelectionKey objects serve as pointers to channels. They can also hold an object attachment, which is how you normally store the state for the connection on that channel.
SelectionKey objects are returned by the register() method when registering a channel with a selector. However, you don’t usually need to retain this reference. The
selectedKeys() method returns the same objects again inside a Set. A single channel can be registered with multiple selectors.

总体而言java网络编程 NIO 封装了好几个类,相比于LInux 多路复用编程难度下降了很多。

这里的 Selector 和 Linux select 系统调用功能不一样,底层实现也不一样,跟 Linux epoll 有点类似,属于事件驱动。

ServerSocketChannel 对应于 Linux 的监听描述符 加 socket
SocketChannel 对应于Linux的连接描述符,可读可写
SelectionKey 对应 就绪事件及描述符

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值