Netty:在另一个方法中使用匿名内部类中定义的通道

时间:2015-05-14 16:47:14

标签: java connection netty channel anonymous-inner-class

我在Netty中实现了服务器 - 客户端连接,我可以在两个连接之间发送和接收数据。

    public void start() 
    {
        // Start the interface
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try 
        {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                 .channel(NioServerSocketChannel.class)
                 .childHandler(new ChannelInitializer<SocketChannel>() {
                     @Override
                     public void initChannel(SocketChannel ch) throws Exception {
                         log.debug("Socket established");
                         ch.pipeline().addLast(new SimulatorInboundHandler());
                         establishedChannel = ch;

                         interfaceEventsListeners.announce().interfaceConnected();

                         ByteBuf buff = Unpooled.wrappedBuffer("Hello\n\r".getBytes());
                         ch.writeAndFlush(buff);

                     }

                 })
                 .option(ChannelOption.SO_BACKLOG, 128)
                 .childOption(ChannelOption.SO_KEEPALIVE, true);

            // Bind and start to accept incoming connections.
            ChannelFuture bindFuture = b.bind(simulatorConfiguration.getSimulationPort());

            bindFuture.await();

            sendData();

        }
        catch (InterruptedException e) 
        {
            log.error("Interrupted", e);
        }
    }

子处理程序创建一个匿名类来构建通道ch

然后我将该频道保存到全局变量establishedChannel

为了将实时数据输入到连接中,我创建了一个方法sendData()

public void sendData()
{
    Channel ch = establishedChannel;
    ch.pipeline().addLast(new SimulatorInboundHandler());
    ByteBuf buff = Unpooled.wrappedBuffer("Hi\n\r".getBytes());

    if(ch != null)
    {
        ch.writeAndFlush(buff);
    }
    else
    {
        log.debug("No channel object attached");
    }

}

ch不断被识别为null。我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

问题是为每个接受的新Channel调用initChannel(...),因此在绑定未来完成后调用sendData()是没有意义的。