ServerSocketChannel超时?不超时?
Netty的org.jboss.netty.channel.socket.nio.NioServerSocketPipelineSink
中有下面一段代码:
public class ServerSocketAdaptor// package-private extends ServerSocket{....... public Socket accept() throws IOException {synchronized (ssc.blockingLock()) { if (!ssc.isBound())throw new IllegalBlockingModeException(); try {if (timeout == 0) { SocketChannel sc = ssc.accept(); if (sc == null && !ssc.isBlocking())throw new IllegalBlockingModeException(); return sc.socket();}[color=red]// Implement timeout with a selector[/color]SelectionKey sk = null;Selector sel = null;ssc.configureBlocking(false);try { SocketChannel sc; if ((sc = ssc.accept()) != null)return sc.socket(); sel = Util.getTemporarySelector(ssc); sk = ssc.register(sel, SelectionKey.OP_ACCEPT); long to = timeout; for (;;) { if (!ssc.isOpen()) throw new ClosedChannelException();long st = System.currentTimeMillis();int ns = sel.select(to);if (ns > 0 && sk.isAcceptable() && ((sc = ssc.accept()) != null)) return sc.socket();sel.selectedKeys().remove(sk);to -= System.currentTimeMillis() - st;[color=red]if (to <= 0) throw new SocketTimeoutException();[/color] }} finally { if (sk != null)sk.cancel(); if (ssc.isOpen())ssc.configureBlocking(true); if (sel != null) Util.releaseTemporarySelector(sel);} } catch (Exception x) {Net.translateException(x);assert false;return null;// Never happens }} }}
按楼主的例子,抛出异常的点在代码的红色部分,可以看到在使用selector模拟实现超时的时候,抛出的超时异常
6 楼 kingquake21 2011-06-09 如果设置了超时,采用ssc.socket().accept()的方式,会先把ssc改为非阻塞模式,然后在finally里面又修改为阻塞模式 7 楼 gongxuxuxu 2012-08-24 接收的超时 一般是看你的事件等待周期的...
比如
while(继续接收吗?)
{
select(单个模块的超时接收事件)
{
//同样的道理. 读超时 也是这样做即可.
}
}