Нет проблем с вызовом channel.write () из разных потоков.Чтение выполняется обработкой событий в пользовательском обработчике, поэтому нет проблем с многопоточностью.Ваша задача - решить, что делать при возникновении события messageReceived.
Основной способ получить канал - использовать ClientBootStrap и сделать это:
ClientBootstrap bootstrap = new ClientBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("LOGGER", new LoggingHandler("CLIENT", true));
return pipeline;
}
});
// Connect to the server, wait for the connection and get back the channel
ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress(host, port));
// Wait until the connection attempt succeeds or fails.
Channel channel = connectFuture.awaitUninterruptibly().getChannel();
Другой способ можетреализовать такой обработчик и добавить обработчик в конвейер на заводе.Тогда вы сможете в любое время получить доступ к каналу, но первое решение кажется лучшим способом сделать это!
public class PublicChannelHandler extends SimpleChannelUpstreamHandler {
Channel channel;
public Channel getChannel(){
if (channel == null) {
throw new IllegalStateException("No underlying Channel is associated with this handler at the moment.");
}
return this.channel;
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
this.channel=ctx.getChannel());
}
}