今天在测试一个问题的时候希望调整java tcp的接收窗口,于是写了一段简单的测试代码:
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("192.168.0.133", 80));
socketChannel.socket().setReceiveBufferSize(100);
socketChannel.socket().setSendBufferSize(100);
socketChannel.write(ByteBuffer.wrap(
("GET / HTTP/1.1\r\n" +
"Host: 192.168.0.133\r\n" +
"Accept: */*\r\n" +
"\r\n").getBytes(Charset.forName("UTF-8"))));
ByteBuffer byteBuffer = ByteBuffer.allocate(100);
try {
while (socketChannel.read(byteBuffer) > 0) {
byteBuffer.flip();
String content = Charset.forName("UTF-8").decode(byteBuffer).toString();
System.out.print(content);
byteBuffer.clear();
}
} finally {
socketChannel.close();
}
本来以为通过将发送和接收窗口设置为100会减小wireshark抓包看到的win, 然而:
这下就有点百思不得骑姐了。查看一下代码,发现在open时同时进行了connect,而后才设置的接收和发送buffer,会不会这里有问题?于是稍微调整了代码一下:
SocketChannel socketChannel = SocketChannel.open();
socketChannel.socket().setReceiveBufferSize(100);
socketChannel.socket().setSendBufferSize(100);
socketChannel.connect(new InetSocketAddress("192.168.0.133", 80));
socketChannel.write(ByteBuffer.wrap(
("GET / HTTP/1.1\r\n" +
"Host: 192.168.0.133\r\n" +
"Accept: */*\r\n" +
"\r\n").getBytes(Charset.forName("UTF-8"))));
ByteBuffer byteBuffer = ByteBuffer.allocate(100);
String content;
try {
while (socketChannel.read(byteBuffer) > 0) {
byteBuffer.flip();
content = Charset.forName("UTF-8").decode(byteBuffer).toString();
System.out.print(content);
byteBuffer.clear();
}
} finally {
socketChannel.close();
}
果然再次抓包发现结果符合预期了: