十、Java NIO ServerSocketChannel
所有文章
https://www.cnblogs.com/lay2017/p/12901123.html
正文
ServerSocketChannel不直接传输数据,但是它可以监听TCP连接,就像是ServerSocket一样
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9999)); while(true){ SocketChannel socketChannel = serverSocketChannel.accept(); //do something with socketChannel... }
打开一个ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
关闭一个ServerSocketChannel
serverSocketChannel.close();
监听tcp连接
while(true){ SocketChannel socketChannel = serverSocketChannel.accept(); //do something with socketChannel... }
accept方法会阻塞等待SocketChannel返回
非阻塞模式
ServerSocketChannel可以被设置为非阻塞模式。在非阻塞模式中accept方法会立即返回,所以可能返回一个null,如果没有tcp连接建立的话。因此,你需要校验返回值SocketChannel是否为null
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9999)); serverSocketChannel.configureBlocking(false); while(true){ SocketChannel socketChannel = serverSocketChannel.accept(); if(socketChannel != null){ //do something with socketChannel... } }