2 回答
TA貢獻1783條經驗 獲得超5個贊
可以動態修改管道。當您收到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();
}
添加回答
舉報
