首页 > 解决方案 > SimpleChannelInboundHandler 从不触发 channelRead0

问题描述

有一天,我决定使用 Tcp 协议创建一个 Netty Chat 服务器。目前,它成功记录连接和断开连接,但我的处理程序中的 channelRead0 永远不会触发。我试过 Python 客户端。Netty 版本:4.1.6.Final

处理程序代码:

public class ServerWrapperHandler extends SimpleChannelInboundHandler<String> {

    private final TcpServer server;

    public ServerWrapperHandler(TcpServer server){

        this.server = server;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        System.out.println("Client connected.");
        server.addClient(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        System.out.println("Client disconnected.");
        server.removeClient(ctx);
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String msg) {
        System.out.println("Message received.");
        server.handleMessage(ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Read complete.");
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

输出:

[TCPServ] Starting on 0.0.0.0:1052
Client connected.
Read complete.
Read complete.
Client disconnected.

客户端代码:

import socket
conn = socket.socket()
conn.connect(("127.0.0.1", 1052))
conn.send("Hello")
tmp = conn.recv(1024)
while tmp:
    data += tmp
    tmp = conn.recv(1024)
print(data.decode("utf-8"))
conn.close()

标签: javaservernetty

解决方案


Btw, the problem was in my initializer: i added DelimiterBasedFrameDecoder to my pipeline, and this decoder is stopping the thread. I dont know why, but i dont needed this decoder, so i just deleted it, and everything started to work.

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        // Create a default pipeline implementation.
        ChannelPipeline pipeline = ch.pipeline();

        // Protocol Decoder - translates binary data (e.g. ByteBuf) into a Java object.
        // Protocol Encoder - translates a Java object into binary data.

        // Add the text line codec combination first,
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); //<--- DELETE THIS
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("handler", new ServerWrapperHandler(tcpServer));
    }

推荐阅读