【发布时间】: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