2 回答
TA贡献1783条经验 获得超4个赞
可以动态修改管道。当您收到get_object消息时,您可以简单地删除StringEncoder并ObjectEncoder在相关的ChannelInboundHandler
ChannelPipeline p = ctx.pipeline();
if (p.get(StringEncoder.class) != null) {
p.remove(StringEncoder.class);
}
p.addLast(new YourObjectEncoder())
或者,如果您知道编码器的名称,则可以进行替换:
p.replace("encoder", "encoder", new YourObjectEncoder());
TA贡献1862条经验 获得超6个赞
当服务器收到消息并将响应写入客户端时,它可以像这段代码一样动态切换编码器。
@Override
protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
MessageContainer messageContainer = new MessageContainer(message, address);
log.debug("\n");
log.debug("Message received: {}", message);
// Handle received message and write result back to the sender
Object response = this.handleMessage(messageContainer);
if (response instanceof String) {
ctx.channel().pipeline().names();
ctx.channel().pipeline().remove(ObjectEncoder.class);
ctx.channel().pipeline().addFirst(new StringEncoder());
}
if (response != null) {
ctx.write(response);
ctx.flush();
}
ctx.close();
}
添加回答
举报