我正在尝试编写一个每分钟向一个频道注入一条消息的类。我已经弄清楚如何使用下面的代码完成此操作,但我认为我的flush方法是错误的。刷新上游消息后,我注意到套接字立即关闭。
public class Pinger extends ChannelOutboundMessageHandlerAdapter<ByteBuf> {
private static final ByteBuf DUMMY = Unpooled.wrappedBuffer("DUMMY".getBytes());
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception{
super.connect(ctx, remoteAddress, localAddress, promise);
ctx.executor().scheduleAtFixedRate(new RepeatTask(ctx), 0, 60, TimeUnit.SECONDS);
}
private final class RepeatTask implements Runnable {
private final ChannelHandlerContext ctx;
public RepeatTask(ChannelHandlerContext ctx){
this.ctx = ctx;
}
public void run() {
if(ctx.channel().isActive()){
ctx.write(DUMMY.copy());
}
}
}
@Override
public void flush(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
ctx.nextOutboundMessageBuffer().add(msg);
ctx.flush();
}
}
我还要注意,这个处理程序位于复杂的管道中间。
答案 0 :(得分:0)
我想我想出了如何使这项工作。 ChannelStateHandlerAdapter是一个更好的继承类。
public class Pinger extends ChannelStateHandlerAdapter {
private static final ByteBuf DUMMY = Unpooled.wrappedBuffer("DUMMY".getBytes());
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelActive();
ctx.executor().scheduleAtFixedRate(new PingTask(ctx), 0, 60, TimeUnit.SECONDS);
}
private final class RepeatTask implements Runnable {
private final ChannelHandlerContext ctx;
public RepeatTask(ChannelHandlerContext ctx){
this.ctx = ctx;
}
public void run() {
if(ctx.channel().isActive()){
ctx.write(DUMMY.copy());
}
}
}
@Override
public void inboundBufferUpdated(ChannelHandlerContext ctx)
throws Exception {
ctx.fireInboundBufferUpdated();
}
}