使用Netty 4,我如何编写一个处理程序,它可以定期注入消息,并且仍然传递消息?
我正在尝试编写一个类,它每分钟向一个通道注入一条消息。我已经知道如何使用下面的代码来实现这一点,但我认为我的flush方法是错误的。刷新上游消息后,我注意到套接字立即关闭使用Netty 4,我如何编写一个处理程序,它可以定期注入消息,并且仍然传递消息?,netty,Netty,我正在尝试编写一个类,它每分钟向一个通道注入一条消息。我已经知道如何使用下面的代码来实现这一点,但我认为我的flush方法是错误的。刷新上游消息后,我注意到套接字立即关闭 public class Pinger extends ChannelOutboundMessageHandlerAdapter<ByteBuf> { private static final ByteBuf DUMMY = Unpooled.wrappedBuffer("DUMMY".getBytes()
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();
}
}
公共类Pinger扩展ChannelOutboundMessageHandlerAdapter{
私有静态final ByteBuf DUMMY=unmooled.wrappedBuffer(“DUMMY.getBytes());
@凌驾
public void connect(ChannelHandlerContext ctx、SocketAddress remoteAddress、SocketAddress localAddress、ChannelPromise承诺)引发异常{
super.connect(ctx、remoteAddress、localAddress、promise);
executor().scheduleAtFixedRate(新的RepeatTask(ctx),0,60,时间单位为秒);
}
私有最终类RepeatTask实现可运行{
专用最终通道HandlerContext ctx;
公共RepeatTask(ChannelHandlerContext ctx){
this.ctx=ctx;
}
公开募捐{
if(ctx.channel().isActive()){
ctx.write(DUMMY.copy());
}
}
}
@凌驾
public void flush(ChannelHandlerContext ctx、ByteBuf msg)引发异常{
ctx.nextOutboundMessageBuffer().add(msg);
ctx.flush();
}
}
<>我也注意到这个处理程序在一个复杂的流水线的中间。 我想我已经知道如何使这个工作了。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();
}
}