@user963241 为@EJP 的答案添加更多颜色。
flip() 使其为 write() (或 get())做好准备
get() 示例;
您可能希望从缓冲区读取数据(假设您最初将其存储在其中)并将其用于其他用途,例如转换为字符串并对其进行操作以供进一步使用。
ByteBuffer buf = ByteBuffer.allocateDirect(80);
private String method(){
buf.flip();
byte[] bytes = byte[10]; //creates a byte array where you can place your data
buf.get(bytes); //reads data from buffer and places it in the byte array created above
return bytes;
}
写()示例;在将数据从套接字通道读取到缓冲区后,您可能希望将其写回套接字通道 - 假设您想要实现类似服务器的东西,它会回显从客户端接收到的相同消息。
因此,您将从通道读取到缓冲区并从缓冲区读取回通道
SocketChannel socketChannel = SocketChannel.open();
...
ByteBuffer buf = ByteBuffer.allocateDirect(80);
int data = socketChannel.read(buf); // Reads from channel and places it into the buffer
while(data != -1){ //checks if not end of reading
buf.flip(); //prepares for writing
....
socketChannel.write(buf) // if you had initially placed data into buf and you want to read
//from it so that you can write it back into the channel
}