我编写了一个客户端类,它处理与不同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()
方法时,将建立与远程服务器的连接并正确发送消息。但是,当同一套接字第二次调用send()
方法时,会在地图中找到Channel
,但writeAndFlush()
操作失败,原因表明该通道已关闭。 / p>
我在代码中的任何地方都看不到我关闭此Channel
。是否有特殊配置可以避免Netty关闭Channel
?
谢谢, 迈克尔
答案 0 :(得分:-1)
远程主机可以在空闲时将其关闭。您需要实施某种心跳以确保通道保持活动状态。