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

先介绍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 对应 就绪事件及描述符

你可能感兴趣的:(Linux,高并发,网络编程,java,NIO,网络编程,nio,linux,高并发,java)