实现说明
除了类 SocketTuning,文件里再无其他定义。
while (accepted.read(buf) != -1) { /* drain until EOF */ } 反复执行,循环体之外没有别的重复。资源写在 try 头部,关闭由编译器生成、异常安全。
使用要点
- 直接运行文件,输出会带上标签,比如
tcp_nodelay=、keepalive=、send_buffer=——输出的每一行都能指回产生它的那次调用。
常见问题
运行「SocketChannel 上的 TCP_NODELAY 选项」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 tcp_nodelay=、keepalive=、send_buffer= 这类标签。
核心语句
server.bind(new InetSocketAddress(0)); // port 0: the kernel picks a free port
int port = ((InetSocketAddress) server.getLocalAddress()).getPort();
String text = StandardCharsets.UTF_8.decode(buf.flip()).toString().trim();
client.shutdownOutput(); // signal the peer that writing is done
}
代码示例
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
public class SocketTuning {
public static void main(String[] args) throws Exception {
try (ServerSocketChannel server = ServerSocketChannel.open()) {
server.bind(new InetSocketAddress(0)); // port 0: the kernel picks a free port
int port = ((InetSocketAddress) server.getLocalAddress()).getPort();
try (SocketChannel client = SocketChannel.open()) {
client.connect(new InetSocketAddress("127.0.0.1", port));
// TCP_NODELAY disables Nagle batching: small interactive packets go out at once
client.setOption(StandardSocketOptions.TCP_NODELAY, true);
client.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
// getOption reads back the values the kernel actually accepted
System.out.println("tcp_nodelay=" + client.getOption(StandardSocketOptions.TCP_NODELAY));
System.out.println("keepalive=" + client.getOption(StandardSocketOptions.SO_KEEPALIVE));
System.out.println("send_buffer=" + client.getOption(StandardSocketOptions.SO_SNDBUF));
client.write(StandardCharsets.UTF_8.encode("ping
"));
client.shutdownOutput(); // signal the peer that writing is done
}
ByteBuffer buf = ByteBuffer.allocate(64);
try (SocketChannel accepted = server.accept()) {
while (accepted.read(buf) != -1) { /* drain until EOF */ }
String text = StandardCharsets.UTF_8.decode(buf.flip()).toString().trim();
System.out.println("received: " + text);
}
}
}
}