2016-03-04 231 views
1

嗨,我有一個Tcp客戶端,我想檢查他是否連接到服務器,我不想檢查他是否與socket.isConnected()或socket.isBound( )我的意思是我想知道,如果套接字連接現在和我不能找到一個方法來做到這一點,因爲在服務器斷開連接,他dosnt送什麼東西給客戶Android的Tcp客戶端檢查連接到服務器

這裏是我的代碼:

public void sendMessage(String message) { 
    if (out != null && !out.checkError()) { 
     out.println(message); 
     out.flush(); 
    } 
} 

public void stopClient() { 
    mRun = false; 
} 

public void run() { 

    mRun = true; 
    try { 
     //connecting 
     InetAddress serverAddr = InetAddress.getByName(SERVERIP); 
     Socket socket = new Socket(serverAddr, SERVERPORT); 
     sss = socket; 


     try { 
      //send the message to the server 
      out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); 
      //receive the message that the server sends back 
      in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

      HelloService.firstTouch(); 


      //in this while the client listens for the messages sent by the server 
      while (mRun) { 
       serverMessage = in.readLine(); 

       if (serverMessage != null && mMessageListener != null) { 
        //call the method messageReceived from MyActivity class to inform main activity that a message has received 
        mMessageListener.messageReceived(serverMessage); 
       } 
       serverMessage = null; 
      } 

     } catch (Exception e) { 

     } finally { 

      socket.close(); 
     } 

    } catch (Exception e) { 

    } 
} 
+0

如果@ EJP的答案不適用於您(嗯雖然),嘗試ping服務器或使用'isReachable()'。 – Onik

+0

嘗試過,但它一直返回假的東西?它非常重要請有人嗎? –

+0

不是'isReachable()'返回'false'意味着服務器斷開? – Onik

回答

0

當服務器斷開連接時,readLine()返回null,您需要檢查它並退出讀取循環並關閉連接(如果有的話)。您目前的檢查僅足以避免NPE。

+0

的事情是,它dos'nt返回任何我已經試過它 –