java - SimpleChannelInboundHandler 从不触发channelRead0

标签 java server netty

有一天,我决定使用 Tcp 协议(protocol)创建一个 Netty 聊天服务器。目前,它成功记录连接和断开连接,但我的处理程序中的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()

最佳答案

顺便说一句,问题出在我的初始化程序中:我将 DelimiterBasedFrameDecoder 添加到我的管道中,并且该解码器正在停止线程。我不知道为什么,但我不需要这个解码器,所以我就把它删除了,一切都开始工作了。

    @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));
    }

关于java - SimpleChannelInboundHandler 从不触发channelRead0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56821015/

相关文章:

java - 使用 Spring Data 和 Hibernate 的 Spring MVC 分页

ubuntu - 在 Ubuntu 上启动时运行 Jupyter-notebook

java - 套接字未从服务器接收或发送消息

c - 服务器只能接受n个客户端

java - 在 netty 4.0 中选择 simplehandler 或 executor

java - Netty4 可读字节太小

asynchronous - 了解 netty 的工作原理

java - Spring将 Autowiring 的对象传递给类构造函数

java - 删除没有删除权限的文件

java - Espresso 单元测试 : How to disable animation in code