java - 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()
解决方案
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));
}
推荐阅读
- c++ - 来自 ta-lib 的错误数据
- reactjs - Redux 表单未使用字段的干净值初始化
- flutter - admod 无法在真实设备中显示
- javascript - 使用 JavaScript 验证正则表达式时返回错误
- android - 向 MapView 片段添加按钮时 MapView 被缩小
- c++ - 将图像从 python 包装器传递给 c++ 函数
- c# - 图像未显示在 Back Office Umbraco 版本 8 的 mediaSection 中
- powershell - powershell 调用命令到变量并写成表格
- sql-server - SQL Server:从字符串中提取 $#,###
- sql-server - TryParse SSIS 忽略源行