首页  

java NIO SocketChannel     所属分类 nio 浏览量 937
public abstract class SocketChannel extends AbstractSelectableChannel
    implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel
    
public abstract class AbstractSelectableChannel extends SelectableChannel


SocketChannel 连接到TCP网络套接字的通道

打开一个SocketChannel并连接到某台服务器
ServerSocketChannel 接受一个新连接 ,创建一个SocketChannel


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

socketChannel.close();


ByteBuffer buf = ByteBuffer.allocate(128);
int bytesRead = socketChannel.read(buf);
-1,表示已经读到了流的末尾(连接关闭了)


String str = "hello java nio";

ByteBuffer buf = ByteBuffer.allocate(128);
buf.clear();
buf.put(str.getBytes());
//切换为读模式
buf.flip();
while(buf.hasRemaining()) {
    channel.write(buf);
}

write()方法无法保证能写多少字节到SocketChannel
循环 调用write 直到全部写入

非阻塞模式,connect 方法可能在连接建立之前就返回

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

while(! socketChannel.finishConnect() ){
    // wait 
}


非阻塞模式 , 将一或多个SocketChannel 注册到 Selector
询问 Selector , 哪些通道已经准备好读写了

上一篇     下一篇
Java NIO pipe

java NIO FileChannel

Java NIO Scatter Gather

Java NIO 内存映射文件

java随机数生成器

ZGC指南