假设我们有一个 JavaSocketChannel
连接到正在等待传入数据的服务器:
SocketChannel server = SocketChannel.open();
server.connect(new InetSocketAddress(ip, port));
我们发送我们的请求如下:
byte[] request = "This is a request for server!".getBytes();
ByteBuffer buffer = ByteBuffer.wrap(request);
buffer.flip();
int write = 0;
while (buffer.hasRemaining())
write += server.write(buffer);
System.out.println(write);
上面的代码返回0
,这意味着它不会向通道写入任何字节!
但是,如果我删除该buffer.flip()
行,它将正常工作并发送数据:
byte[] request = "This is a request for server!".getBytes();
ByteBuffer buffer = ByteBuffer.wrap(request);
int write = 0;
while (buffer.hasRemaining())
write += server.write(buffer);
System.out.println(write);
为什么是这样 ?!