gpt4 book ai didi

java - SimpleChannelInboundHandler 从不触发channelRead0

转载 作者:行者123 更新时间:2023-12-02 03:43:48 30 4
gpt4 key购买 nike

有一天,我决定使用 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com