1,创建SocketChannel:
SocketChannel socketChannel = SocketChannel.open();
2,关闭SocketChannel:
socketChannel.close();
3,从SocketChannel读取数据,存到Buffer中:
首先分配一个ByteBuffer:
ByteBuffer buf = ByetBuffer.allocate(48);
int Bytelen = socketChannel.read(buf); //读取到buf中
4,往SocketChannel写数据:
首先buffer中有数据:
String newData = "hello gch" ;
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();//转换为读模式
然后往SocketChannel中写入:
while(buf.hasRemaining()){
socketChannel.write(buf); //往SocketChannel写数据
}