[英]connecting to server but server has not started java
我正在創建一個通過套接字連接到服務器(java)的android應用程序。我已經在swing中創建了一個服務器應用程序,其中包含開始按鈕,該按鈕可以打開我指定的端口。
所以我的問題是,當客戶端嘗試連接但服務器尚未啟動時,我該如何處理情況呢? 而且我還想為客戶端創建建議啟動服務器的對話框
我已經嘗試過此代碼,但是它使我的應用程序掛起:
我對此非常困惑!
這是代碼:
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();
}
我認為您必須等待其連接-是否沒有回調? 該代碼說:
/**
* 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客戶端並使用它?
您的代碼不是永久掛起,它只是在等待超時,因為服務器沒有響應,這時您將收到UnknownHostException
異常。 捕獲並在捕獲中顯示您的“啟動服務器”消息。
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();
}
您的套接字代碼永遠無法工作。 它必須在線程或AsyncTask中執行。 如果您這樣做,則無法顯示Toast()。
那么你正在做什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.