2010-04-14 6 views
-1

나는 운동으로 자바에서 간단한 웹 서버를 쓰고있다. 프로그램을 실행하면 즉시 콘솔에 "오류 : null"을 출력하는 무한 루프가 시작됩니다. 이 시작되는 나는 알아 내기 위해 이클립스 디버거를 사용하여 시도자바 : 무한 오류 "null"

System.out.println("Error: " + e.getMessage()); 

을 몇 가지 시도/catch 문을 가지고,하지만 난 디버거에서 그것을 실행하면 정상적으로 동작합니다. 코드의 Heres는 두 개의 관련 클립 :

public void run() { 
     // Declare server socket 
     ServerSocket serversocket = null; 

     try { 
      // Initialize serversocket on the port passed to 
      // the constructor 
      serversocket = new ServerSocket(port); 
      System.out.println("Server started on port " 
        + Integer.toString(port)); 
     } catch (Exception e) { 
      System.out.println("Fatal Error: " + e.getMessage()); 
     } 

     while (true) { 
      try { 
       // Wait for connections 
       Socket connectionsocket = serversocket.accept(); 
       // Get client IP 
       InetAddress client = connectionsocket.getInetAddress(); 
       System.out.println(client.getHostName() + " connected."); 

       // Read the request into a buffer 
       BufferedReader input = new BufferedReader(
        new InputStreamReader(connectionsocket.getInputStream())); 

       // Prepare the output stream for sending headers 
       // and requested file to the client 
       DataOutputStream output = 
        new DataOutputStream(connectionsocket.getOutputStream()); 

       http_handler(input, output); 
      } catch (Exception e) { 
       System.out.println("Error: " + e.getMessage()); 
      } 
     } 
    } 

private void http_handler(BufferedReader input, DataOutputStream output) { 
    int method = 0; // 1 get, 2 head, 0 not supported 
    String http = new String(); 
    String path = new String(); 
    String file = new String(); 
    String user_agent = new String(); 
    try { 
     // Two types of requests we can handle: 
     // Get /index.html HTTP/1.0 
     // HEAD /index.html HTTP/1.0 
     String tmp = input.readLine(); // Read from the stream 
     String tmp2 = new String(tmp); 
     tmp.toUpperCase(); 
     if (tmp.startsWith("GET")) { 
      method = 1; 
     } 
     if (tmp.startsWith("HEAD")) { 
      method = 2; 
     } 

     if (method == 0) { 
      try { 
       // If the request is unsupported, send the error 
       output.writeBytes(construct_http_header(501, 0)); 
       output.close(); 
       return; 
      } catch (Exception e2) { 
       System.out.println("Error: " + e2.getMessage()); 
      } 
     } 

     // Get whats between the spaces in the request 
     // without the beginning slash 
     int start = 0; 
     int end = 0; 

     for (int a = 0; a < tmp2.length(); a++) { 
      if (tmp2.charAt(a) == ' ' && start != 0) { 
       end = a; 
       break; 
      } 
      if (tmp2.charAt(a) == ' ' && start == 0) { 
       start = a; 
      } 
     } 
     path = tmp2.substring(start + 2, end); 

    } catch(Exception e) { 
     System.out.println("Error: " + e.getMessage()); 
    } 
    FileInputStream requestedfile = null; 

    try { 
     // Try to open the file 
     requestedfile = new FileInputStream(path); 
    } catch (Exception e) { 
     try { 
      output.writeBytes(construct_http_header(404, 0)); 
      output.close(); 
     } catch (Exception e2) {} 
     ; 
     System.out.println("Error: " + e.getMessage()); 
    } 

    try { 
     int type_is = 0; 
     // Find out what the filename ends with so we can 
     // put the right MIME type in the header 

     if (path.endsWith(".zip") || path.endsWith(".exe") 
       || path.endsWith(".tar")) { 
      type_is = 3; 
     } else if (path.endsWith(".jpg") || path.endsWith(".jpeg")) { 
      type_is = 1; 
     } else if (path.endsWith(".gif")) { 
      type_is = 2; 
     } else { 
      type_is = 5; 
     } 
     // write out the header, 200 -> OK 
     output.writeBytes(construct_http_header(200, type_is)); 

     // if the request was HEAD, we don't print the body 
     if (method == 1) { 
      while (true) { 
       // read the file from the filestream and ouput through 
       // the client outpustream 
       int b = requestedfile.read(); 
       if (b == -1) { 
        break; // end of file 
       } 
       output.write(b); 
      } 
     } 
     // Clean up 
     output.close(); 
     requestedfile.close(); 
    } catch (Exception e) {} 
} 

** 내가 스택 추적을 인쇄하고

Socket connectionsocket = serversocket.accept(); 

I에 NullPointerException이 제공됩니다 ** 편집 이 방법이 연결을 기다릴 것으로 생각했습니다. 내가하는 일을 못하게하려면 어떻게해야합니까?

+5

메시지를 인쇄하는 대신 전체 스택 추적 * 및 예외 유형 *을 콘솔에 덤프하십시오. 그러면 더 많은 정보를 얻을 수 있습니다. –

+0

"오류 :"줄을 변경하여 오류가 발생한 위치를 알려 - 스택 추적도 인쇄하십시오 (각 예외에서) – KevinDTimm

+0

이러한 오류 메시지는 일반적으로 널 포인터가 어딘가에서 참조 해제되었음을 의미합니다. –

답변

0

ServerSocket 초기화가 실패하면 연결을 허용 할 수있는 것이 없기 때문에 무한한 널 포인터 예외로 끝납니다.

1

첫 번째 추측은 코드의 첫 번째 청크에있는 while (true)이 될 수 있지만 읽기에는 눈에 띄는 것이 없습니다. 단계별 디버거를 사용하는 대신 디버그 문을 인쇄 해 보셨습니까? 디버그 모드에서 작업한다는 것은 무슨 뜻인지 알고 있습니다.

그러나 좋은 몇 가지 단계를 추적하기 위해 수행 :

  1. 변경 Error 1:, Error 2: 그의 출력을 사용하여 같은 것을 할 때마다 Error: 문은 코드의 덩어리가 예외를 던지는 것이다 좁힐 .
  2. 쉽게 다룰 수있는 것보다 훨씬 많은 것을 좁히는 스택 추적을 인쇄하십시오.
  3. 출력의 코드를 시각적으로 살펴보기 위해 모든 라인 (또는 필요한 경우 몇 줄마다)을 인쇄하십시오. 창

이렇게하면 문제를 줄 수있는 영역을 좁히고 더 자세한 세분화 된 출력 문과 정확히 어떤 줄과 이유를 사용할 수 있습니다.