Hob*_*ist 0 java loops for-loop
我一直在闯入Netty网络库,试图学习如何编写一些基本的NIO网络代码,当我遇到一些看起来不对我的东西时,一个没有任何内部的for循环,这里是代码:
for (;;) {
SocketChannel acceptedSocket = channel.socket.accept();
if (acceptedSocket == null) {
break;
}
registerAcceptedChannel(channel, acceptedSocket, thread);
}
Run Code Online (Sandbox Code Playgroud)
我立即检查了循环的文档教程,位于此处,找不到与此声明相关的任何内容.
直接在此代码上方的注释说明如下:
// accept connections in a for loop until no new connection is ready
Run Code Online (Sandbox Code Playgroud)
但这并没有真正向我解释它是如何工作的,或者为什么,它只是说它正在做什么.
如果您需要整个方法,这里是:
@Override
protected void process(Selector selector) {
Set<SelectionKey> selectedKeys = selector.selectedKeys();
if (selectedKeys.isEmpty()) {
return;
}
for (Iterator<SelectionKey> i = selectedKeys.iterator(); i.hasNext();) {
SelectionKey k = i.next();
i.remove();
NioServerSocketChannel channel = (NioServerSocketChannel) k.attachment();
try {
// accept connections in a for loop until no new connection is ready
for (;;) {
SocketChannel acceptedSocket = channel.socket.accept();
if (acceptedSocket == null) {
break;
}
registerAcceptedChannel(channel, acceptedSocket, thread);
}
} catch (CancelledKeyException e) {
// Raised by accept() when the server socket was closed.
k.cancel();
channel.close();
} catch (SocketTimeoutException e) {
// Thrown every second to get ClosedChannelException
// raised.
} catch (ClosedChannelException e) {
// Closed as requested.
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to accept a connection.", t);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// Ignore
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
for (;;)是一个无限循环,相当于while (true).因为for循环没有终止语句,所以它永远不会终止.
for循环中的所有三个组件都是可选的: for (initialization; termination; increment)
| 归档时间: |
|
| 查看次数: |
177 次 |
| 最近记录: |