2 回答

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
可以動(dòng)態(tài)修改管道。當(dāng)您收到get_object消息時(shí),您可以簡(jiǎn)單地刪除StringEncoder并ObjectEncoder在相關(guān)的ChannelInboundHandler
ChannelPipeline p = ctx.pipeline();
if (p.get(StringEncoder.class) != null) {
p.remove(StringEncoder.class);
}
p.addLast(new YourObjectEncoder())
或者,如果您知道編碼器的名稱,則可以進(jìn)行替換:
p.replace("encoder", "encoder", new YourObjectEncoder());

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
當(dāng)服務(wù)器收到消息并將響應(yīng)寫(xiě)入客戶端時(shí),它可以像這段代碼一樣動(dòng)態(tài)切換編碼器。
@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();
}
添加回答
舉報(bào)