Sockets ApacheNetty在套接字上发送一个大字符串,但在客户端获取不完整的字符串
我正在通过netty在TCP套接字上发送一个2000个字符的字符串,客户端和服务器端,我设置了以下管道:Sockets ApacheNetty在套接字上发送一个大字符串,但在客户端获取不完整的字符串,sockets,tcp,netty,Sockets,Tcp,Netty,我正在通过netty在TCP套接字上发送一个2000个字符的字符串,客户端和服务器端,我设置了以下管道: socketChannel.pipeline().addLast( new StringEncoder(), new StringDecoder(), new LineBasedFrameDecoder(Integer.MAX_VALUE),
socketChannel.pipeline().addLast(
new StringEncoder(),
new StringDecoder(),
new LineBasedFrameDecoder(Integer.MAX_VALUE),
myHandler);
在服务器端,我有一个ChannelInboundHandlerAdapter
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// some code
ctx.writeAndFlush(line);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
}
在客户端,我有一个SimpleChannelInboundHandler。但是我的字符串不完整。为什么?我怎样才能解决这个问题
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {//msg is incomplete}
我找到了解决办法。
新的LineBasedFrameDecoder(Integer.MAX_值)是无意义的。因为java中每个字符串的最大字符数是65536,所以请尝试使用新的LineBasedFrameDecoder(65536)或任何您需要的大小。
在服务器端,每个消息应以\n或\r\n结尾。例如,如果从文本文件中读取一行,则需要在该行末尾添加\n 实际上是65535。实际上是65535,但这与此无关,因为其中没有单个
字符串。问题是缺少行终止符。