你好,我有一个 Netty 服务器,它有一个应该接受字符串的处理程序。它似乎只能接收最多 1024 字节的内容。我怎样才能增加缓冲区大小。我已经试过了
bootstrap.setOption("child.sendBufferSize", 1048576);
bootstrap.setOption("child.receiveBufferSize", 1048576);
没有成功。
处理程序如下
public class TestHandler extends SimpleChannelHandler {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
ChannelBuffer buf = (ChannelBuffer) e.getMessage();
String response = "";
if (buf.readable()) {
response = buf.toString(CharsetUtil.UTF_8);
System.out.println("CONTENT: " + response);
}
System.out.println(response);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
e.getCause().printStackTrace();
Channel ch = e.getChannel();
ch.close();
}
最佳答案
您使用的是 UDP 吗?如果是这样,数据包将最大为 1024 字节。此代码注释在 QOTM 代码示例中:
Allow packets as large as up to 1024 bytes (default is 768). You could increase or decrease this value to avoid truncated packets or to improve memory footprint respectively.
Please also note that a large UDP packet might be truncated or dropped by your router no matter how you configured this option. In UDP, a packet is truncated or dropped if it is larger than a certain size, depending on router configuration. IPv4 routers truncate and IPv6 routers drop a large packet. That's why it is safe to send small packets in UDP.
如果您使用的是 TCP,则应在处理程序之前将帧解码器和字符串解码器添加到管道中;像这样:
pipeline.addLast("frameDecoder", new DelimiterBasedFrameDecoder(80960, Delimiters.lineDelimiter()));
pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("myHandler", new TestHandler());
请注意,您需要修改测试处理程序,因为 MessageEvent 实际上将包含您的字符串。
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
String response = (String) e.getMessage();
System.out.println(response);
}
有道理吗?
关于java - Netty 增加 ChannelBuffer 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13086564/