【发布时间】:2014-08-02 05:02:55
【问题描述】:
我写了一个客户端类来处理到不同 TCP 服务器的多个 TCP 连接,如下所示:
private int nThreads;
private Charset charset;
private Bootstrap bootstrap;
private Map<String, Channel> channels = new HashMap<String, Channel>();
public MyClass() {
bootstrap = new Bootstrap()
.group(new NioEventLoopGroup(nThreads))
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder(charset));
}
});
}
public void send(MyObject myObject) {
final String socket = myobject.getSocket();
//Check if a channel already exists for this socket
Channel channel = channels.get(socket);
if(channel == null) {
/* No channel found for this socket. */
//Extract host and port from socket
String[] hostport = socket.split(":", 2);
int port = Integer.parseInt(hostport[1]);
//Create new channel
ChannelFuture connectionFuture;
try {
connectionFuture = bootstrap.connect(hostport[0], port).await();
} catch (InterruptedException e) {
return;
}
//Connection operation is completed, check status
if(!connectionFuture.isSuccess()) {
return;
}
//Add channel to the map
channel = connectionFuture.channel();
channels.put(notifSocket, channel);
}
//Write message on channel
final String message = myObject.getMessage();
channel.writeAndFlush(message).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if(!future.isSuccess()) {
//Log cause
return;
}
}
});
}
}
当send() 方法为给定的套接字第一次调用时,将建立与远程服务器的连接并正确发送消息。但是,当对同一个socket第二次调用send()方法时,在map中找到了Channel,但是writeAndFlush()操作失败,原因是channel被关闭了。
我在我的代码中没有看到我关闭此Channel 的任何地方。是否有特殊配置可以避免 Netty 关闭Channel?
谢谢, 迈克尔
【问题讨论】: