【问题标题】:Netty: Using a channel defined in the anonymous inner class within another methodNetty:在另一个方法中使用匿名内部类中定义的通道
【发布时间】:2015-07-26 09:24:58
【问题描述】:

我已经在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 不断被标识为空。我该如何解决这个问题?

【问题讨论】:

  • 你能用 log.debug 检查 initChannel 的 "ch" 是否不为空

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


【解决方案1】:

问题在于,对于每个被接受的新 Channel,都会调用 initChannel(...),因此在绑定 future 完成后调用 sendData() 没有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    相关资源
    最近更新 更多