我使用的是Netty 3.2.7.我正在尝试在我的客户端编写功能,这样如果在一定时间(例如30秒)之后没有写入消息,则会向服务器发送"保持活动"消息.
经过一番挖掘,我发现WriteTimeoutHandler应该让我这样做.我在这里找到了这个解释:https://issues.jboss.org/browse/NETTY-79.
Netty文档中给出的示例是:
public ChannelPipeline getPipeline() {
// An example configuration that implements 30-second write timeout:
return Channels.pipeline(
new WriteTimeoutHandler(timer, 30), // timer must be shared.
new MyHandler());
}
Run Code Online (Sandbox Code Playgroud)
在我的测试客户端,我做到了这一点.在MyHandler中,我还覆盖了exceptionCaught()方法:
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
if (e.getCause() instanceof WriteTimeoutException) {
log.info("Client sending keep alive!");
ChannelBuffer keepAlive = ChannelBuffers.buffer(KEEP_ALIVE_MSG_STR.length());
keepAlive.writeBytes(KEEP_ALIVE_MSG_STR.getBytes());
Channels.write(ctx, Channels.future(e.getChannel()), keepAlive);
}
}
Run Code Online (Sandbox Code Playgroud)
无论客户端在什么时间内没有向通道写入任何内容,我从未调用过覆盖的exceptionCaught()方法.
查看WriteTimeoutHandler的源代码,其writeRequested()实现是:
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
long timeoutMillis = getTimeoutMillis(e);
if (timeoutMillis > 0) …Run Code Online (Sandbox Code Playgroud)