Netty 客户端持久套接字
有人能告诉我需要做什么来重用netty中客户端创建的套接字连接吗?如果我在netty的客户端创建一个通道,多个并发线程是否可以在不同步的情况下使用同一通道?在netty 3.2中,处理这种情况的正确方法是什么Netty 客户端持久套接字,netty,Netty,有人能告诉我需要做什么来重用netty中客户端创建的套接字连接吗?如果我在netty的客户端创建一个通道,多个并发线程是否可以在不同步的情况下使用同一通道?在netty 3.2中,处理这种情况的正确方法是什么 -TK是,同一通道可由不同线程使用,因为所有方法都是线程安全的。是,同一通道可由不同线程使用,因为所有方法都是线程安全的。从不同线程调用Channel.write()没有问题。 读取是通过在自定义处理程序中处理事件来完成的,因此不存在多线程问题。当messageReceived事件被触发时
-TK是,同一通道可由不同线程使用,因为所有方法都是线程安全的。是,同一通道可由不同线程使用,因为所有方法都是线程安全的。从不同线程调用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());
}
}
从不同线程调用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());
}
}