2017-03-17 65 views
0

我創建通過sockets.I其連接到服務器(JAVA)的Android應用程序已經創建了揮杆包含啓動按鈕,打開我已指定端口的服務器應用程序。連接到服務器,但是服務器還沒有啓動的Java

所以我的問題是我怎麼能處理situatuion當客戶端試圖連接服務器,但尚未啓動的手段我還沒有點擊開始按鈕? ,我也想爲客戶創建對話框,建議開始我試圖在服務器

這個代碼,但它讓我掛應用:

我有這個真糊塗!

這裏是代碼:

try { 
     cs = new Socket(IPADD,PORT); 
     if(cs.isConnected()) 
     { Toast.makeText(ipInfo.this,"Connected",Toast.LENGTH_SHORT).show(); 
      Intent inst = new Intent(ipInfo.this,homeActivity.class); 
      inst.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(inst); 
      finish(); 
     }else { 
      Toast.makeText(ipInfo.this,"Server is disconnected\nStart server in desktop",Toast.LENGTH_SHORT).show(); 
      } 
    }catch (IOException e) 
    {Toast.makeText(ipInfo.this,e.getMessage(),Toast.LENGTH_SHORT).show(); 
    }catch (Exception e) 
    {Toast.makeText(ipInfo.this,e.getMessage(),Toast.LENGTH_SHORT).show(); 
} 
+0

你的代碼不工作的方式是什麼?它錯誤嗎? –

+0

不存在沒有錯誤,但是當我嘗試連接的應用程序掛起 – Neel

+0

@SteveSmith意味着服務器處理不當還沒有開始,然後我試圖連接 – Neel

回答

0

您的代碼不被永久懸掛,它只是在等待超時,因爲服務器沒有響應,此時你會得到一個UnknownHostException例外。抓住這個並在catch中顯示你的「Start Server」消息。

try { 
    Socket socket = new Socket(); 
    // 1000 is the timeout 
    socket.connect(new InetSocketAddress(IPADD, PORT), 1000); 
    Toast.makeText(ipInfo.this,"Connected",Toast.LENGTH_SHORT).show(); 
    Intent inst = new Intent(ipInfo.this,homeActivity.class); 
    inst.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    startActivity(inst); 
    finish(); 
} catch (IOException e) 
    Toast.makeText(ipInfo.this,"Server is disconnected\nStart server in desktop",Toast.LENGTH_SHORT).show(); 
} catch (Exception e) { 
    Toast.makeText(ipInfo.this,e.getMessage(),Toast.LENGTH_SHORT).show(); 
} 
+0

所以我必須在與未知主機異常catch塊添加,然後在設置超時的,對嗎?如果不是,那麼你可以請讓代碼的一部分 – Neel

+0

我已經做了捕捉部分,但我應該在哪裏放置'setSoTimeout' – Neel

+0

請參閱我編輯的答案。 –

0

我認爲你必須等待它連接 - 是有沒有回調? 代碼說:

所以
/** 
* Returns the connection state of the socket. 
* <p> 
* Note: Closing a socket doesn't clear its connection state, which means 
* this method will return <code>true</code> for a closed socket 
* (see {@link #isClosed()}) if it was successfuly connected prior 
* to being closed. 
* 
* @return true if the socket was successfuly connected to a server 
* @since 1.4 
*/ 
public boolean isConnected() { 
    // Before 1.3 Sockets were always connected during creation 
    return connected || oldImpl; 
} 

isConnected()只返回一個靜態值,這是不太可能居然這麼立即改變你實例化的插座後。 Android有很多網絡庫。除非你特別需要這樣做,否則我建議使用Retorfit或Volley(尤其是改進版),或者只是建立一個OKHTTP客戶端並使用它?

+0

你可以建議一些修改代碼的一部分,因爲我是新來這個某種:/ – Neel

0

您的套接字代碼無法工作。它必須在線程或AsyncTask中執行。如果你這樣做,你就不能顯示Toast()。

所以你在做什麼?

+0

我想向客戶端顯示「服務器尚未啓動請啓動服務器」 – Neel

相關問題