ServerSocketChannel.accept()vs ServerSocket.accept()

时间:2017-08-28 13:58:53

标签: java sockets nio

如果我将ServerSocketChannel配置为非阻塞,那么调用

之间是否有任何区别

ServerSocketChannel.accept()。socket()和ServerSocket.accept()?

从下面

ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking( false );
ServerSocket ss = ssc.socket();
InetSocketAddress isa = new InetSocketAddress( port );
ss.bind( isa );

Selector selector = Selector.open(); 
ssc.register( selector, SelectionKey.OP_ACCEPT ); 
System.out.println( "Listening on port "+port );
ByteBuffer buffer = ByteBuffer.allocate( 4096 );

while (true) {

int numKeys = selector.select();
if (numKeys>0) {
 Set skeys = selector.selectedKeys();
Iterator it = skeys.iterator();

while (it.hasNext()) {

  SelectionKey rsk = (SelectionKey)it.next();
  int rskOps = rsk.readyOps();

  if ((rskOps & SelectionKey.OP_ACCEPT) ==
      SelectionKey.OP_ACCEPT) {

    Socket socket = ss.accept()  

   }
  }
 }
}

1 个答案:

答案 0 :(得分:0)

不同之处在于,一个返回SocketChannel,另一个返回Socket

由于您可能会选择结果,因此在使用SsrverSocket.accept()时确实没有任何意义,因为您只需要从中获取SocketChannel,进入非阻塞模式,使用Selector进行注册,并使用它完成所有I / O,很少或不再使用Socket