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) {
}
}
如果@ EJP的答案不適用於您(嗯雖然),嘗試ping服務器或使用'isReachable()'。 – Onik
嘗試過,但它一直返回假的東西?它非常重要請有人嗎? –
不是'isReachable()'返回'false'意味着服務器斷開? – Onik