码迷,mamicode.com
首页 > 编程语言 > 详细

九、Java NIO SocketChannel

时间:2020-05-17 20:38:23      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:两种   pen   www   open   color   异步   blog   com   sele   

所有文章

https://www.cnblogs.com/lay2017/p/12901123.html

 

正文

SocketChannel表示一个连接到TCP通道的Socket上。有两种方式可以创建SocketChannel

1.你可以直接open一个SocketChannel,然后connect

2.当ServerSocketChannel接收到连接的时候

open一个SocketChannel

SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));

close一个SocketChannel

socketChannel.close(); 

从SocketChannel读取数据

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = socketChannel.read(buf);

写入数据到SocketChannel

String newData = "New String to write to file..." + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());

buf.flip();

while(buf.hasRemaining()) {
    channel.write(buf);
}

非阻塞模式

你可以将SocketChannel设置为非阻塞模式。在非阻塞模式下,connect、read、write操作都变成了异步

connect

非阻塞模式下,connect方法变成异步。你需要主动去判断连接是否完成

socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));

while(! socketChannel.finishConnect() ){
    //wait, or do something else...    
}

write

非阻塞模式下,write方法直接返回。因此,你需要在循环中不断调用write方法。但是在上面的write示例中本身就是循环调用,所以其实写法没有不同

read

非阻塞模式下,read方法直接返回,这时候可能并未读取到任何数据。因此,你需要注意read方法返回值,从而判断当前有没有读取到数据。

非阻塞模式下的选择器

非阻塞模式的SocketChannel和Selector搭配使用非常方便。通过将SocketChannel注册到Selector中,当SocketChannel可用的时候通过事件响应异步处理

 

九、Java NIO SocketChannel

标签:两种   pen   www   open   color   异步   blog   com   sele   

原文地址:https://www.cnblogs.com/lay2017/p/12906661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!