Netty:在另一个方法中使用匿名内部 class 中定义的通道
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);
}
}
子处理程序创建一个匿名 class 来构建通道 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(...) 会为每个被接受的新频道调用,因此在绑定 future 完成后调用 sendData() 是没有意义的。
我在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);
}
}
子处理程序创建一个匿名 class 来构建通道 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(...) 会为每个被接受的新频道调用,因此在绑定 future 完成后调用 sendData() 是没有意义的。