java SocketChannel and ServerSocketChannel
1 SocketChannel
1.1 打開一個SocketChannel
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("http://www.baidu.com", 80));
1.2 關(guān)閉一個SocketChannel
socketChannel.close();
1.3 讀取一個SocketChannel
ByteBuffer buf = ByteBuffer.allocate(48);
int byteRead = socketChannel.read(buf);
2 ServerSocketChannel
2.1 ServerSocketChannel in blocking mode
??? ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
??? serverSocketChannel.socket().bind(new InetSocketAddress(1111));
??? while(true) {
??????? SocketChannel socketChannel = serverSocketChannel.accept();
??????? // do something with socketChannel.......
??? }
2.2 ServerSocketChannel in non-blocking mode
??? ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
??? serverSocketChannel.socket().bind(new InetSocketAddress(1111));
??? serverSocketChannel.configureBlocking(false);
??? while(true) {
??????? SocketChannel socketChannel = serverSocketChannel.accept();
??????? if (socketChannel != null)
??????? {
??????????? // do something with socketChannel.......
??????? }
??? }
在non-blocking mode時,沒有人來connect的時候accept()就會直接返回。這也是non-blocking的意義所在,對于文件而言,總是可以讀寫的,不存在block一說,也就沒有non-blocking mode了。
?
轉(zhuǎn)載于:https://www.cnblogs.com/hustdc/p/8109785.html
總結(jié)
以上是生活随笔為你收集整理的java SocketChannel and ServerSocketChannel的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的 Rokid 之路 附:记事本技能全
- 下一篇: 关于ueditor多图上传加水印