2012-06-26 9 views
0

우리 회사가 밤새도록 실행하는 배치 파일을 가지고 있으므로 서버 (MatLab)/클라이언트 (Java/Eclispe) 코드를 사용하여 단일 파일로 잘 작동하고 참된 루프를 넣을 수 있습니다 모든 것을 중심으로 제대로 작동하도록했습니다. 유일한 문제는 socket.accept() 호출로 서버가 항상 클라이언트를 찾는다는 것입니다. 그러나 클라이언트에 연결할 클라이언트가 없다면 영원히 거기에 있습니다. 프로그램을 닫으려면 작업 관리자로 가서 강제로 닫아야합니다.소켓 수신 중지 수신 허용

그렇다면 타이머를 넣을 수있는 방법이 있습니다. 아무도 특정 시간 후에 연결을 시도하지 않으면 더 이상 배치 파일을 실행하지 않아도 연결을 취소하고 프로그램을 종료 할 수 있습니다.

+0

이 항목을 설정할 수 있습니다 [소켓 타임 아웃을 사용하여이 답] (http://stackoverflow.com/a/2983861/2805324) – LateralFractal

답변

0

이 코드는 동의에 시간 제한()

private ServerSocket listener; 
    private int timeout; 
    private Thread runner; 
    private boolean canceled; 

    ... 

    // returns true if cancel signal has been received 
    public synchronized boolean isCanceled() 
    { 
     return canceled; 
    } 

    // returns true if this call does the canceling 
    // or false if it has already been canceled 
    public synchronized boolean cancel() 
    { 
     if (canceled) { 
      // already canceled due to previous caller 
      return false; 
     } 

     canceled = true; 
     runner.interrupt(); 
     return true; 
    } 

    public void run() 
    { 
     // to avoid race condition (see below) 
     listener.setSoTimeout(timeout); 

     while (! isCanceled()) { 
      // DANGER!! 
      try { 
       Socket client = listener.accept(); 
       // hand client off to worker thread... 
      } 
      catch (SocketTimeoutException e) { 
       // ignore and keep looping 
      } 
      catch (InterruptedIOException e) { 
       // got signal while waiting for connection request 
       break; 
      } 
     } 

     try { 
      listener.close(); 
     } 
     catch (IOException e) { 
      // ignore; we're done anyway 
     } 
    }