簡體   English   中英

Netty:在另一個方法中使用匿名內部類中定義的通道

[英]Netty: Using a channel defined in the anonymous inner class within another method

我已經在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被連續標識為空。 我如何解決這個問題?

問題在於,將為每個接受的新通道調用initChannel(...),因此在綁定將來完成之后調用sendData()是沒有意義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM