2012-07-26 130 views
1

我試圖讓(android)客戶端與服務器進行通信。發送數據客戶端 - >服務器工作正常,但我希望服務器響應。客戶端代碼:Java服務器 - 客戶端套接字通信

try { 
       Socket s = new Socket("192.168.0.36", 12390); 
       s.setSoTimeout(5000); 

       JSONObject json = new JSONObject(); 
       json.put("emergency", false); 
       json.put("imei", imei); 
       json.put("lat", l.getLatitude()); 
       json.put("lon", l.getLongitude()); 
       json.put("acc", l.getAccuracy()); 
       json.put("time", l.getTime()); 


       BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
       s.getOutputStream())); 
       out.write(json.toString()); 
       out.newLine(); 
       out.write("###"); 
       out.flush(); 
       Log.d(TAG, "sent"); 


       String inputLine = null; 
       String result = ""; 
       BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); 

       Log.d(TAG, "open input"); 
       while ((inputLine = in.readLine()) != null) { 
        Log.d(TAG, "while"); 
        if (inputLine.contains("###")) { 
         break; 
        } 
        result = result.concat(inputLine); 

       } 

       Log.d(TAG, "closing socket"); 
       s.close(); 

服務器端:

Socket c = null; 
    while (true) { 
     try { 
      c = s.accept(); 
     } catch (IOException e) { 
      System.out.println("Accept failed: " + port); 
      System.exit(-1); 
     } 
     try { 

      BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); 
      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(c.getOutputStream())); 



      String inputLine = null; 
      String result = ""; 
      while ((inputLine = in.readLine()) != null) { 

       if (inputLine.contains("###")) { 
        System.out.println("received ###"); 
         out.write("Hello phone"); 
         out.newLine(); 
         out.write("###"); 
         out.newLine(); 
         out.flush(); 

       } 

       result = result.concat(inputLine); 


      } 
      System.out.println(result); 

      out.close(); 

服務器正確讀取來自客戶端的消息和接收###應發回的消息後,卻是從未收到由客戶。客戶端超時

    while ((inputLine = in.readLine()) != null) { 
        Log.d(TAG, "while"); 
        if (inputLine.contains("###")) { 
         break; 
        } 

永遠不會進入while循環。我在這裏錯過了什麼?任何想法讚賞!

回答

2

從客戶端:

out.write(json.toString()); 
out.newLine(); 
out.write("###"); 
out.flush(); 

你忘了添加後發送 「###」 新行,因爲你的服務器使用的readLine()

while ((inputLine = in.readLine()) != null) { 
//... 
} 

所以,我相信您的服務器可以不會收到此消息。嘗試把

out.newLine(); 

發送「###」後。

+0

這實際上是它!我沒有注意到它,因爲服務器記錄了「System.out.println(」received ###「);」,但那個人解決了它。謝謝一堆! – FWeigl 2012-07-26 09:46:10

0

我可能在這裏是非常錯誤的,但根據我的經驗,我總是在我開始通信之前打開進出流。請嘗試移動

BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); 

旁邊

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 

萬一你打開你的輸入流,並開始閱讀之前你的數據包過期。

+0

試過了,沒有幫助,但感謝您的輸入! – FWeigl 2012-07-26 09:00:51