2013-03-20 84 views
0

我試圖創建Android客戶端和Java服務器簡單的應用程序 Android客戶端能夠發送郵件服務器(JAVA) 而當我嘗試讀取服務器的回覆 錯誤:套接字關閉。 線(IF((receiveMessage = receiveRead.readLine())!= NULL))安卓:socket通信

public class ClientConnectorTask extends AsyncTask<String, Void, Integer> { 
    private Socket client; 
    private PrintWriter printwriter; 
    protected Integer doInBackground(String...strings) { 
     // validate input parameters 
     if (strings.length <= 0) { 
      return 0; 
     } 
     // connect to the server and send the message 
     try { 
      client = new Socket("192.168.1.4", 7777); 
      printwriter = new PrintWriter(client.getOutputStream(),true); 

      //while(true){ 
      InputStream istream = client.getInputStream(); 
      BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream)); 

      String receiveMessage; 
      while (true){ 
      // printwriter.write(strings[0]); 
       printwriter.print(strings[0]); 
       printwriter.flush(); 
       printwriter.close(); 
       if((receiveMessage = receiveRead.readLine()) != null) //receive from server 
       { 
        System.out.println(receiveMessage); // displaying at DOS prompt 
       } 
      } 
      //} 

      //client.close(); 
     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return 0; 
    } 
    protected void onPostExecute(Long result) { 
     return; 
    } 
} 
+0

我不確定這一點,這就是爲什麼它是一個評論。我相信這個''printwriter.close();''可能會關閉套接字。但是,正如我所說我不確定。如果你刪除它,它會拋出錯誤嗎?另外,你確定你沒有在服務器端關閉它嗎? – Fred 2013-03-21 00:08:51

+0

感謝您的reply.in服務器端我不關閉。如果我不這樣做,那麼數據不會到達服務器 – 2013-03-22 21:25:55

回答

0

關閉PrintWriter內循環沒有意義,而且readLine()呼叫無厘頭前關閉它無論是。關閉Socket的輸入或輸出流會關閉另一個流和套接字。

+0

感謝您的回覆,將檢查出 – 2013-03-22 21:26:40