2013-07-01 100 views
1

嗨,我有一個服務器套接字,它偵聽來自客戶端套接字的請求,而我的代碼似乎沒有從其輸入流中從客戶端套接字發送的數據中檢索數據。下面Java Socket服務器沒有從客戶端套接字接收數據

是服務器套接字代碼監聽連接和處理請求

public void startlistener() { 
serverSocket = new ServerSocket(PORT); 
      listening = true; 
      thread.start(); 
      Log.print(TAG, "startlistener"); 

     } 

     public void stopListener() { 
      thread.stop(); 
      listening = false; 
      Log.print(TAG, "stopListener"); 
     } 

    public void run() { 
       while (listening) { 
        try { 

         Log.d(TAG, "inside server listener loop"); 
         Socket accept = serverSocket.accept(); 

         String data = getData(accept); 

         httpHandler.handleRequest(data, accept); 

        } catch (Exception e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
       } 

    private String getData(Socket socket) throws IOException { 
      InputStream in = socket.getInputStream(); 
      Log.print(TAG, "getData"); 
      int c = 0; 

      StringBuffer buffer = new StringBuffer(); 
    //goes as far as here and then freezes/doesnt retrieve anything from the input stream 
      while ((c = in.read()) != -1) { 
       buffer.append((char) c); 
      } 
      return buffer.toString(); 

     } 

這裏是我的測試用例

private static final String HTTP_REQUEST = "HTTP/1.0 408 Request Time-out" 
     + newLine + "Cache-Control: no-cache" + newLine 
     + "Connection: close" + newLine + "Content-Type: text/html"; 

public void testSocketConnection() { 

     try { 
      httpProxy = new HttpProxy(testHttpHandler); 
      httpProxy.startlistener(); 
      testSocket = new Socket("localhost", HttpProxy.PORT); 
      OutputStream outputStream = testSocket.getOutputStream(); 
      InputStream inputStream = testSocket.getInputStream(); 

      outputStream.write(HTTP_REQUEST.getBytes()); 
} catch (UnknownHostException e) { 
      httpProxy.stopListener(); 
      e.printStackTrace(); 
      fail(e.toString()); 
     } catch (IOException e) { 
      httpProxy.stopListener(); 
      e.printStackTrace(); 
      fail(e.toString()); 
     } 


} 

回答

2

您的客戶端不關閉套接字。您的服務器讀取套接字直到EOS,由於您的客戶端沒有關閉套接字,它將永遠不會到達。

NB在接受線程中不處理客戶端I/O。開始一個單獨的線程。

+0

ok,只要我在客戶端調用socket.write()。我應該在適當的時候關閉套接字? – jonney

+0

每當你想讓接收環路停止。或者,更改接收循環。查看DataOutputStream和DataInputStream的方法,如果您想知道如何在保持套接字打開的情況下發送數據。或者,使用對象序列化,XML等。 – EJP

相關問題