2014-11-29 5 views
0

Netty 네트워킹 라이브러리를 찢어 내고 있습니다. 기본 NIO 네트워킹 코드를 작성하는 법을 배우려하고 있는데, 나에게 맞지 않는 무언가를 만났을 때, for-loop 안에 아무 것도없는 코드가 있습니다. 코드는 다음과 같습니다. :Java for (;;) 루프?

for (;;) { 
    SocketChannel acceptedSocket = channel.socket.accept(); 
    if (acceptedSocket == null) { 
     break; 
    } 
    registerAcceptedChannel(channel, acceptedSocket, thread); 
} 

나는 즉시 here에 위치한 루프의 문서 튜토리얼을 확인하고이 사항에 관련된 아무것도 찾을 수 없습니다.

// accept connections in a for loop until no new connection is ready 

그러나 작동, 또는 왜, 그냥이 무엇을하고 있는지 말한다 방법이 정말 나에게 설명하지 않습니다

직접 코드 위의 해설은 다음을 말한다. 당신은 모든 방법을해야하는 경우

는 여기있다 :

@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 
      } 
     } 
    } 
} 
+0

그것은 무한 루프입니다. – squiguy

+0

for 루프의 모든 부분은 선택 사항입니다. 확인해야 할 조건이 없으며 실행 단계가 없기 때문에 이는 대다수의 루프로 볼 수 있습니다. – Makoto

+0

...'break;'와 함께 종료됩니다 –

답변

6

for (;;)while (true)에 해당 무한 루프입니다. for-loop에는 종료 문이 없으므로 절대로 종료되지 않습니다. A의 루프에서

세 가지 구성 요소는 선택 사항입니다 : for (initialization; termination; increment)

+0

아! 이것은 의미가 있습니다! 나는 당신이 이렇게 진술을 무효화 할 수 있다는 것을 몰랐다. 그래서 기본적으로 for (int i = 0;; i ++)는 영원히 증가 할 것이지만, 맞습니까? – Hobbyist

+0

@ Christian.tucker 정확합니다. – August

+0

매우 편리합니다. 타이머가 만료되면이를 올바르게 표시 할 것입니다. – Hobbyist