Java Netty 4.0发送长度超过16 KB的字符串消息?

Java Netty 4.0发送长度超过16 KB的字符串消息?,java,string,server,client,netty,Java,String,Server,Client,Netty,我有一个简单的客户端服务器,在Java中使用Netty4.0。问题是我不知道为什么Netty服务器看不到从Netty客户端发送的超过16KB的消息。我尝试使用较短的消息,服务器可以读取它 Netty客户端的代码 class ClientCommunicator { public void sendMessage() { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(g

我有一个简单的客户端服务器,在Java中使用Netty4.0。问题是我不知道为什么Netty服务器看不到从Netty客户端发送的超过16KB的消息。我尝试使用较短的消息,服务器可以读取它

Netty客户端的代码

 class ClientCommunicator {
        public void sendMessage() {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(
                        new LoggingHandler(LogLevel.INFO),
                        new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                        new StringEncoder(),
                        new StringDecoder(),
                        new ClientCommunicatorHandler(message));
                }
            });

            // Start the connection attempt.
            log.info("##### SENDING TO HOST: " + this.host + " and POST " + this.port);
            bootstrap.connect(this.host, this.port).sync().channel().closeFuture().sync();
            log.debug("##### Message sent successfully. (!)");

        }
    }

class ClientCommunicatorHandler extends SimpleChannelInboundHandler<String> {

    private final Message inboxMessage;

    ClientCommunicatorHandler(@NotNull Message message) {
        this.inboxMessage = message;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = RasFedStatusMessageHandler.RASFED_IDENTIFIER +
                         this.inboxMessage.toSerializedString().replace("\n", "").replace("\r", "") + "\n";
        log.debug("#### Sending message: {}", message.substring(0, 200));
        ctx.writeAndFlush(message);
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("Error caught in client communication service: ", cause);
        ctx.close();
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("#### What I'm doing here?");
    }
}
类ClientCommunicator{
公共无效发送消息(){
Bootstrap Bootstrap=新的Bootstrap();
bootstrap.group(组)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY,true)
.handler(新的通道初始值设定项(){
@凌驾
public void initChannel(SocketChannel ch)引发异常{
ch.pipeline().addLast(
新LoggingHandler(LogLevel.INFO),
新的DelimiterBasedFrameDecoder(Integer.MAX_值,Delimiters.lineDelimiter()),
新的StringEncoder(),
新的字符串解码器(),
新客户端通讯器处理程序(消息));
}
});
//开始连接尝试。
log.info(“######发送到主机:“+this.HOST+”和POST”+this.port);
bootstrap.connect(this.host,this.port).sync().channel().closeFuture().sync();
log.debug(“已成功发送消息(!”);
}
}
类ClientCommunicatorHandler扩展了SimpleChannelInboundHandler{
私有最终消息inboxMessage;
ClientCommunicatorHandler(@NotNull Message){
this.inboxMessage=消息;
}
@凌驾
公共无效channelActive(ChannelHandlerContext ctx)引发异常{
字符串消息=RasFedStatusMessageHandler.RASFED_标识符+
此.inboxMessage.toSerializedString().replace(“\n”和“).replace(“\r”和“)+”\n”;
log.debug(“####发送消息:{}”,message.substring(0200));
ctx.writeAndFlush(消息);
ctx.close();
}
@凌驾
公共无效例外情况(ChannelHandlerContext ctx,可丢弃原因){
log.error(“客户端通信服务中捕获的错误:,原因”);
ctx.close();
}
@凌驾
受保护的无效channelRead0(ChannelHandlerContext ctx,字符串msg)引发异常{
log.info(“我在这里做什么?”);
}
}
Netty服务器从客户端接收消息的代码

public class ServerCommunicator {

    private final int port;

    public ServerCommunicator(int port) {
        this.port = port;
    }

    public void run(final LocalNode localNode, final InpeerNodeRegistry inpeerNodeRegistry, final OutpeerNodeRegistry outpeerNodeRegistry) throws Exception {
        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.TRACE))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LoggingHandler(LogLevel.TRACE),
                                    new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                                    new NettyObjectEncode(),
                                    new StringDecoder(),
                                    new ServerCommunicatorHandler(localNode, inpeerNodeRegistry, outpeerNodeRegistry));
                        }
                    });

            // Start the server.
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

            // Wait until the server socket is closed.
            channelFuture.channel().closeFuture().sync();
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

class NettyObjectEncode extends MessageToByteEncoder<ByteArrayResponse> {

    private final Logger log = LoggerFactory.getLogger(NettyObjectEncode.class);

    @Override
    protected void encode(ChannelHandlerContext chc, ByteArrayResponse byteArrayResponse, ByteBuf bb) throws Exception {
        byte[] bytes = byteArrayResponse.getDatas();
        String data = new String(bytes);
        if (data.contains("bigdata")) {
            log.info("#### Received Message: " + data);
        }
        bb.writeBytes(bytes);
    }
}




// Server handlers
    class ServerCommunicatorHandler extends SimpleChannelInboundHandler<String> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
            InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
            MessageContainer messageContainer = new MessageContainer(message, address);
            log.debug("\n");

            // Handle received message and write result back to the sender
            Object response = this.handleMessage(messageContainer);
            if (response instanceof String) {
                ctx.channel().pipeline().remove(NettyObjectEncode.class);
                ctx.channel().pipeline().addFirst(new StringEncoder());
            }

            if (response != null) {
                ctx.write(response);
                ctx.flush();
            }
            ctx.close();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            log.error("Error caught in server communication service: ", cause);
            ctx.close();
        }
    }
公共类服务器通讯器{
私人最终国际港口;
公用服务器通讯器(int端口){
this.port=端口;
}
public void run(final LocalNode LocalNode,final InpeerNodeRegistry InpeerNodeRegistry,final OutpeerNodeRegistry OutpeerNodeRegistry)引发异常{
//配置服务器。
EventLoopGroup bossGroup=新的NioEventLoopGroup();
EventLoopGroup workerGroup=新的NioEventLoopGroup();
试一试{
ServerBootstrap ServerBootstrap=newserverbootstrap();
serverBootstrap.group(bossGroup、workerGroup)
.channel(NioServerSocketChannel.class)
.handler(新的LoggingHandler(LogLevel.TRACE))
.childHandler(新的通道初始值设定项(){
@凌驾
public void initChannel(SocketChannel ch)引发异常{
ch.pipeline().addLast(
新的LoggingHandler(LogLevel.TRACE),
新的DelimiterBasedFrameDecoder(Integer.MAX_值,Delimiters.lineDelimiter()),
新NettyObjectEncode(),
新的字符串解码器(),
新的ServerCommunicatorHandler(localNode、inpeerNodeRegistry、outpeerNodeRegistry));
}
});
//启动服务器。
ChannelFuture=serverBootstrap.bind(port.sync();
//等待服务器套接字关闭。
channelFuture.channel().closeFuture().sync();
}最后{
//关闭所有事件循环以终止所有线程。
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
类NettyObjectEncode扩展了MessageToByteEncoder{
私有最终记录器log=LoggerFactory.getLogger(NettyObjectEncode.class);
@凌驾
受保护的无效编码(ChannelHandlerContext chc、ByteArrayResponse、ByteBuf bb)引发异常{
byte[]bytes=byteArrayResponse.getDatas();
字符串数据=新字符串(字节);
if(data.contains(“bigdata”)){
log.info(“#####接收消息:“+数据”);
}
bb.写入字节(字节);
}
}
//服务器处理程序
类ServerCommunicatorHandler扩展了SimpleChannelInboundHandler{
@凌驾
受保护的无效channelRead0(ChannelHandlerContext ctx,字符串消息)引发异常{
InetSocketAddress地址=(InetSocketAddress)ctx.channel().remoteAddress();
MessageContainer MessageContainer=新的MessageContainer(消息,地址);
log.debug(“\n”);
//处理收到的邮件并将结果写回发件人
对象响应=this.handleMessage(messageContainer);
if(字符串的响应实例){
ctx.channel().pipeline().remove(NettyObjectEncode.class);
ctx.channel().pipeline().addFirst(新的StringEncoder());
}
if(响应!=null){
写(应答);
ctx.flush();
}
ctx.close();
}
@凌驾
公共无效例外情况(ChannelHandlerContext ctx,可丢弃原因){
log.error(“服务器通信服务中捕获的错误:”,原因);
ctx.close();
}
}