我正在使用netty 4.0.0-CR3,遵循服务器端的示例: https ://github.com/netty/netty/blob/master/example/src/main/java/io/netty/example/telnet /TelnetServerPipelineFactory.java
我已经按如下方式构建了我的管道:
private static final StringDecoder DECODER = new StringDecoder(CharsetUtil.UTF_8);
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("decoder", DECODER);
// and then business logic
pipeline.addLast("serverHandler", new ServerHandler());
}
和处理程序:
public class ServerHandler extends ChannelInboundMessageHandlerAdapter<String> {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class);
public void messageReceived(ChannelHandlerContext ctx, String request)
throws Exception {
// Displays the message
LOGGER.info("Received: " + request);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
LOGGER.error("Unexpected exception from downstream.", cause);
ctx.close();
}
}
我创建了一个简单的 C# 客户端,它将字符串编码为字节,然后发送到服务器。但是,我没有看到 StringDecoder 的 decode() 或处理程序的 messageReceived() 被调用。
然后我在管道中删除了 StringDecoder() ,并将处理程序更改为:
public class Handler extends ChannelInboundByteHandlerAdapter {
@Override
protected void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in)
throws Exception {
System.out.println("called " + in.toString(CharsetUtil.UTF_8));
}
}
现在它可以正常工作了。从功能上讲,两个管道都应该正常工作吗?为什么第一个设置不起作用?客户端代码是一样的。
非常感谢!