2014-07-15 3 views
0

스레드가 있습니다. 마녀가 소켓 채널 선택기를 테스트하고 있습니다. 소켓 채널이 연결되어 있고 읽을 수있는 경우 메시지 처리기 스레드가 시작되어 메시지가 읽히고 처리됩니다. 많은 것들이 있기 때문에 처리기 스레드를 시작해야하며 처리하기위한 시간이 필요합니다.Java SocketChannel이 다른 스레드에서 닫혔습니다.

메인 쓰레드

while (true) { 
     try { 
      // Wait for an event one of the registered channels 
      this.selector.select(); 

      // Iterate over the set of keys for which events are available 
      Iterator selectedKeys = this.selector.selectedKeys().iterator(); 
      while (selectedKeys.hasNext()) { 
       SelectionKey key = (SelectionKey) selectedKeys.next(); 
       selectedKeys.remove(); 

       if (!key.isValid()) { 
        continue; 
       } 

       // Check what event is available and deal with it 
       if (key.isAcceptable()) { 
        this.accept(key); 
       } 
       if (key.isReadable()) { 
        this.read(key); 
       } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      Thread.sleep(200); 
     } catch (InterruptedException ex) { 
      ex.printStackTrace(); 
     } 
    } 

판독 기능 : 핸들러 스레드가 실행될 때

private void read(SelectionKey key) throws IOException { 
     // For an accept to be pending the channel must be a server socket channel. 
     SocketChannel clientSocketChanel = (SocketChannel) key.channel(); 
     WebCommandHandler commands = new WebCommandHandler(clientSocketChanel); 
     if (clientSocketChanel.isConnected()) { 
      Thread cThread = new Thread(commands); 
      cThread.setName("Message handler"); 
      cThread.start(); 
     } 
    } 

문제는, 주어진 SocketChannel에 이미 폐쇄된다. 스레드를 실행하지 않으면 run() 메소드 만 호출하고 소켓은 닫히지 않으므로 주 스레드 반복이 주어진 SocketChannel을 닫고 있다고 생각합니다. 누군가 해결 방법을 알아내는 것을 도울 수 있습니까? 핸들러 스레드가 작동을 멈출 때까지 어떻게 SocketChannel을 열어 둘 수 있습니까?

아마 편집

내가 새 스레드를 시작하기 전에, 선택기에서 SocketChannel에 "를 등록 해제"해야는 ... 어떻게 Seelctor에서 SocketChannel에 등록을 취소 할 수 있습니까?

답변

0

그래, 해결책을 찾았습니다 ... 그럼 Selector에서 SocketChannel을 등록 취소해야합니다 ... 그리고 key.cancel() 함수를 호출하여이 작업을 수행 할 수 있습니다.