`
Donald_Draper
  • 浏览: 996389 次
社区版块
存档分类
最新评论

ServerSocketChannel定义

    博客分类:
  • NIO
阅读更多
Channel接口定义:http://donald-draper.iteye.com/blog/2369111
AbstractInterruptibleChannel接口定义:http://donald-draper.iteye.com/blog/2369238
SelectableChannel接口定义:http://donald-draper.iteye.com/blog/2369317
SelectionKey定义:http://donald-draper.iteye.com/blog/2369499
SelectorProvider定义:http://donald-draper.iteye.com/blog/2369615
AbstractSelectableChannel定义:http://donald-draper.iteye.com/blog/2369742
NetworkChannel接口定义:http://donald-draper.iteye.com/blog/2369773
先来回顾一下ServerSocketChannel继承结构树:
//ServerSocketChannel
public abstract class ServerSocketChannel
    extends AbstractSelectableChannel
    implements NetworkChannel

//AbstractSelectableChannel
public abstract class AbstractSelectableChannel
    extends SelectableChannel

//SelectableChannel
public abstract class SelectableChannel
    extends AbstractInterruptibleChannel
    implements Channel

今天来看一下ServerSocketChannel的定义
package java.nio.channels;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketOption;
import java.net.SocketAddress;
import java.nio.channels.spi.AbstractSelectableChannel;
import java.nio.channels.spi.SelectorProvider;

/**
 * A selectable channel for stream-oriented listening sockets.
 *面向流监听socket可选择通道。
 *  A server-socket channel is created by invoking the {@link #open() open}
 * method of this class.  It is not possible to create a channel for an arbitrary,
 * pre-existing {@link ServerSocket}. A newly-created server-socket channel is
 * open but not yet bound.  An attempt to invoke the {@link #accept() accept}
 * method of an unbound server-socket channel will cause a {@link NotYetBoundException}
 * to be thrown. A server-socket channel can be bound by invoking one of the
 * {@link #bind(java.net.SocketAddress,int) bind} methods defined by this class.
 *ServerSocketChannel通过open方法,创建一个ServerSocketChannel通道。如果已经存在一个
ServerSocket,将不会创建ServerSocketChannel。新创建的ServerSocketChannel是没有绑定地址的。
调用没有绑定地址的ServerSocketChannel的accept方法,将会抛出NotYetBoundException。
可以通过bind方法绑定地址。
 * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
 * setOption} method. Server-socket channels support the following options:
 可用#setOption方法,配置socket选项,ServerSocketChannel支持的选项配置如下:
 * <blockquote>
 * <table border>
 *   <tr>
 *     <th>Option Name</th>
 *     <th>Description</th>
 *   </tr>
 *   <tr>接受缓冲区大小
 *     <td> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </td>
//StandardSocketOptions
 *     <td> The size of the socket receive buffer </td>
  public static final SocketOption<Integer> SO_RCVBUF =
        new StdSocketOption<Integer>("SO_RCVBUF", Integer.class);
 *   </tr>
 *   <tr>是否可以重用地址
 *     <td> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </td>
 *     <td> Re-use address </td>
 //StandardSocketOptions
 public static final SocketOption<Boolean> SO_REUSEADDR =
        new StdSocketOption<Boolean>("SO_REUSEADDR", Boolean.class);
 *   </tr>
 * </table>
 * </blockquote>
 * Additional (implementation specific) options may also be supported.
 *
 * <p> Server-socket channels are safe for use by multiple concurrent threads.
 ServerSocketChannel是线程安全的
 * 

 *
 * @author Mark Reinhold
 * @author JSR-51 Expert Group
 * @since 1.4
 */

public abstract class ServerSocketChannel
    extends AbstractSelectableChannel
    implements NetworkChannel
{

    /**
     * Initializes a new instance of this class.
     */
    protected ServerSocketChannel(SelectorProvider provider) {
        super(provider);
    }

    /**
     * Opens a server-socket channel.
     *打开一个ServerSocketChannel
     *  The new channel is created by invoking the {@link
     * java.nio.channels.spi.SelectorProvider#openServerSocketChannel
     * openServerSocketChannel} method of the system-wide default {@link
     * java.nio.channels.spi.SelectorProvider} object.
     *通过系统默认的SelectorProvider实现创建一个ServerSocketChannel
     * <p> The new channel's socket is initially unbound; it must be bound to a
     * specific address via one of its socket's {@link
     * java.net.ServerSocket#bind(SocketAddress) bind} methods before
     * connections can be accepted.  

     *新创建的ServerSocketChannel初始是没有绑定的,在接受连接之前必须绑定一个SocketAddress
     * @return  A new socket channel
     *
     * @throws  IOException
     *          If an I/O error occurs
     */
    public static ServerSocketChannel open() throws IOException {
        return SelectorProvider.provider().openServerSocketChannel();
    }

    /**
     * Returns an operation set identifying this channel's supported
     * operations.
     *返回通道支持的操作事件集
     *  Server-socket channels only support the accepting of new
     * connections, so this method returns {@link SelectionKey#OP_ACCEPT}.
      ServerSocketChannel只支持接受连接操作事件
     * 

     *
     * @return  The valid-operation set
     */
    public final int validOps() {
        return SelectionKey.OP_ACCEPT;
    }


    // -- ServerSocket-specific operations --

    /**
     * Binds the channel's socket to a local address and configures the socket
     * to listen for connections.
     *绑定ServerSocketChannel到本地的socket地址,并配置socket监听连接,
     具体实现看bind(SocketAddress local, int backlog)方法
     *  An invocation of this method is equivalent to the following:
     * <blockquote><pre>
     * bind(local, 0);
     * </pre></blockquote>
     *
     * @param   local
     *          The local address to bind the socket, or {@code null} to bind
     *          to an automatically assigned socket address
     *
     * @return  This channel
     *
     * @throws  AlreadyBoundException               {@inheritDoc}
     * @throws  UnsupportedAddressTypeException     {@inheritDoc}
     * @throws  ClosedChannelException              {@inheritDoc}
     * @throws  IOException                         {@inheritDoc}
     * @throws  SecurityException
     *          If a security manager has been installed and its {@link
     *          SecurityManager#checkListen checkListen} method denies the
     *          operation
     *
     * @since 1.7
     */
    public final ServerSocketChannel bind(SocketAddress local)
        throws IOException
    {   
        //委托给bind(SocketAddress local, int backlog)
        return bind(local, 0);
    }

    /**
     * Binds the channel's socket to a local address and configures the socket to
     * listen for connections.
     *绑定ServerSocketChannel到本地的socket地址,并配置socket监听连接
     * <p> This method is used to establish an association between the socket and
     * a local address. Once an association is established then the socket remains
     * bound until the channel is closed.
     *这个方法用于建立socket与本地socket地址的联系。只要联系建立,在通道关闭之前,socket
     能绑定着地址。
     * <p> The {@code backlog} parameter is the maximum number of pending
     * connections on the socket. Its exact semantics are implementation specific.
     * In particular, an implementation may impose a maximum length or may choose
     * to ignore the parameter altogther. If the {@code backlog} parameter has
     * the value {@code 0}, or a negative value, then an implementation specific
     * default is used.
     *backlog参数是socket运行接受的最大连接数。具体的含义要根据具体的实现,有的是最大连接数,
     有的可能忽略这个参数。如果参数为0或者一个负数,将会使用默认的实现机制

     * @param   local 本地socket地址
     *          The address to bind the socket, or {@code null} to bind to an
     *          automatically assigned socket address
     * @param   backlog 最大连接数
     *          The maximum number of pending connections
     *
     * @return  This channel
     *
     * @throws  AlreadyBoundException 地址已经绑定
     *          If the socket is already bound
     * @throws  UnsupportedAddressTypeException 地址不支持
     *          If the type of the given address is not supported
     * @throws  ClosedChannelException 通道关闭
     *          If this channel is closed
     * @throws  IOException  IO操作异常
     *          If some other I/O error occurs
     * @throws  SecurityException
     *          If a security manager has been installed and its {@link
     *          SecurityManager#checkListen checkListen} method denies the
     *          operation
     *
     * @since 1.7
     */
    public abstract ServerSocketChannel bind(SocketAddress local, int backlog)
        throws IOException;

    /**
     * @throws  UnsupportedOperationException           {@inheritDoc}
     * @throws  IllegalArgumentException                {@inheritDoc}
     * @throws  ClosedChannelException                  {@inheritDoc}
     * @throws  IOException                             {@inheritDoc}
     *设置选项
     * @since 1.7
     */
    public abstract <T> ServerSocketChannel setOption(SocketOption<T> name, T value)
        throws IOException;

    /**
     * Retrieves a server socket associated with this channel.
     *返回与通道关联的ServerSocket
     * <p> The returned object will not declare any public methods that are not
     * declared in the {@link java.net.ServerSocket} class.  

     *
     * @return  A server socket associated with this channel
     */
    public abstract ServerSocket socket();

    /**
     * Accepts a connection made to this channel's socket.
     * 接受一个连接到通道socket的请求。
     *  If this channel is in non-blocking mode then this method will
     * immediately return <tt>null</tt> if there are no pending connections.
     * Otherwise it will block indefinitely until a new connection is available
     * or an I/O error occurs.
     *如果通道是非阻塞模式,,如果连接已经达到最大数量,则立即返回null;
     否则不确定地阻塞直到一个新的连接可用或者IO错误发生
     * <p> The socket channel returned by this method, if any, will be in
     * blocking mode regardless of the blocking mode of this channel.
     * 如果通道是阻塞模式,则将返回一个SocketChannle,并忽略阻塞模式
     * <p> This method performs exactly the same security checks as the {@link
     * java.net.ServerSocket#accept accept} method of the {@link
     * java.net.ServerSocket} class.  That is, if a security manager has been
     * installed then for each new connection this method verifies that the
     * address and port number of the connection's remote endpoint are
     * permitted by the security manager's {@link
     * java.lang.SecurityManager#checkAccept checkAccept} method.  

     *此方执行精确的安全检查
     * @return  The socket channel for the new connection,
     *          or <tt>null</tt> if this channel is in non-blocking mode
     *          and no connection is available to be accepted
     *
     * @throws  ClosedChannelException
     *          If this channel is closed
     *
     * @throws  AsynchronousCloseException
     *          If another thread closes this channel
     *          while the accept operation is in progress
     *
     * @throws  ClosedByInterruptException 如果其他线程中断当前线程,则关闭通道,设置当前线程的中断位。
     *          If another thread interrupts the current thread
     *          while the accept operation is in progress, thereby
     *          closing the channel and setting the current thread's
     *          interrupt status
     *
     * @throws  NotYetBoundException 地址没有绑定
     *          If this channel's socket has not yet been bound
     *
     * @throws  SecurityException 安全异常
     *          If a security manager has been installed
     *          and it does not permit access to the remote endpoint
     *          of the new connection
     *
     * @throws  IOException IO操作异常
     *          If some other I/O error occurs
     */
    public abstract SocketChannel accept() throws IOException;

}

从上面可以看出ServerSocketChannel主要是绑定socket地址,监听Socket连接。

0
0
分享到:
评论

相关推荐

    JAVA备忘-网络编程[定义].pdf

    ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(9000)); // 设置非堵塞模式 ssc.configureBlocking(false); // 向选择器注册服务器套接字通道,关注接受...

    Java NIO的介绍及工作原理

    1. **创建Selector和ServerSocketChannel**:首先创建一个Selector对象,并使用`ServerSocketChannel`创建服务器端Channel,将其设置为非阻塞模式。 2. **绑定端口**:将ServerSocketChannel绑定到特定的端口号。 3....

    Thrift demo

    在 `testThrift` 中的 NIO 示例可能包含 `Selector.open()`, `ServerSocketChannel.bind()`, `SelectionKey` 和 `SocketChannel` 的使用。 4. **Thrift Client** 客户端代码同样由 Thrift 编译器生成,它提供了一...

    Android开发进阶之NIO非阻塞包[定义].pdf

    Channel类似于管道,用于数据的读写,例如SocketChannel和ServerSocketChannel。Selector则是一个多路复用器,它能够监控多个Channel的状态,当某个Channel准备就绪时,Selector会通知用户程序进行相应的读写操作,...

    笔记,4、深入Netty1

    `NioEventLoop`执行了`EventLoop`接口,它不仅处理I/O操作,还负责调度和执行用户定义的任务。每个`NioEventLoop`都有自己的线程,确保了并发和并行性。 4. **NioEventLoopGroup**: 可以看作是一组`NioEventLoop`的...

    seata源码研究.docx

    - `transport.threadFactory.serverExecutorThreadPrefix`:定义服务器执行线程前缀,默认为`NettyServerBizHandler`。 - **Netty的NIO通讯**: - **NIO的核心组件**:Channel(通道)、Buffer(缓冲区)、...

    java nio.doc

    - **`ServerSocketChannel`**:用于接受客户端连接。 - **`SocketChannel`**:用于与客户端进行通信。 ##### 选择器(Selectors) 选择器是 NIO 中处理多个通道的机制。它可以同时监控多个通道的状态,例如是否...

    java异步socket调用[文].pdf

    - `java.nio.channels`:定义了通道(Channel)和选择器(Selector),用于异步I/O操作。通道可以注册到选择器上,指定感兴趣的操作事件,如连接就绪、数据可读或可写。 - `java.nio.charset`:处理字符集编码和解码。 ...

    java nio 网络编程指南

    - **SelectableChannel**:这是一个接口,定义了可以支持非阻塞I/O操作的Channel的行为。它包括`ServerSocketChannel`和`SocketChannel`等具体实现。SelectableChannel提供了一种机制,让Channel能够在阻塞和非阻塞...

    java文件传输[归类].pdf

    文件路径可以是相对路径,基于用户定义的系统属性`FILE_PATH`。此外,客户端应能连续输入命令,无需等待服务器响应。 4. **设计要求与说明**: - 文件传输服务器FileServer和客户端FileClient需要实现。 - Echo...

    以netty4.1源码中的EchoServer为例对netty的源码进行分析.docx

    - `childHandler` 定义了新建立连接后的处理逻辑。 4. **ServerBootstrap.bind(port)** 方法执行绑定: - 绑定过程首先会验证 `group` 和 `channelFactory` 是否已设置。 - 然后调用 `AbstractBootstrap` 的 `...

    非阻塞通信

    HTTP协议定义了客户端(浏览器)和服务器之间的交互过程,包括请求报文和响应报文的格式、状态码、头字段等内容。在Java中,可以使用`HttpURLConnection`或者第三方库如Apache HttpClient来实现HTTP客户端,而服务器...

    java异步socket调用.pdf

    在实际的Java异步Socket通信应用中,程序员需要定义如何管理不同的连接和它们的状态,例如接受新的连接请求时,需要为每个新的SocketChannel创建新的线程,或者使用事件驱动模型来管理所有活动的SocketChannel。...

    使用Java_NIO编写高性能的服务器.doc

    根据提供的部分代码示例,我们可以看到`NIOServer`类定义了一些基本的NIO组件,如`ByteBuffer`、`SelectionKey`、`Selector`等,并且定义了一个内部类`HandleClient`用于处理客户端请求。这部分代码展示了如何使用...

    java编程思想笔记

    此外,`java.nio`包的`SocketChannel`和`ServerSocketChannel`提供了更高效的数据传输方式。 以上是Java编程思想笔记中涵盖的主要知识点,这些内容不仅帮助初学者建立起对Java语言的全面认识,也是进阶开发者必备的...

    java NOI 学习

    - `ServerSocketChannel`:用于监听并接受新的TCP连接。 2. **Selectors**:`Selector`是一个核心组件,用于监控多个`Channel`的IO事件。通过`Selector`,开发者可以管理多个`Channel`,并以非阻塞方式处理它们。...

    基于java NIO的socket通信demo

    `Constants.java`文件可能包含了通信过程中的常量定义,比如服务器的IP地址、端口号,以及可能使用的字符集等。这些常量在整个通信过程中起着关键作用,确保了客户端和服务器之间的数据交互一致性。 总的来说,这个...

    netty学习之ServerChannel

    这个参数定义了系统能处理的最大并发连接请求,超过这个数量的连接请求会被暂时拒绝。 7. **多路复用技术**:Netty利用Java NIO的Selector机制,通过一个工作线程就可以同时处理多个连接,极大地提高了服务器的并发...

Global site tag (gtag.js) - Google Analytics