我是Android新手,對套接字編程有點新鮮。我有兩個設備,運行Android 5.1
,與WiFi直接連接(不確定是否相關)。我有一個服務,服務器在套接字上偵聽請求,然後將回復返回給客戶端。Android WiFi直連客戶端套接字超時
同樣,客戶端代碼發送請求並偵聽來自服務器的回覆。服務器正在發送響應,但客戶端永遠不會收到消息並且套接字超時。
服務器測試代碼:
while (true) {
try {
Log.i(TAG, "test waiting for a request");
mServer = new ServerSocket(PORT);
Socket socket = mServer.accept(); //Block to receive message //
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i(TAG, "Message received! " + in.readLine());
String msg = "This is my reply.";
OutputStream outputStream = socket.getOutputStream();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(msg);
out.flush();
out.close();
} catch (SocketException e) {
Log.e(TAG, "Socket Accept Interrupted", e);
} catch (IOException e) {
Log.e(TAG, "Socket Failure", e);
} finally {
if (mServer != null && mServer.isBound()) {
try {
mServer.close();
} catch (IOException ioException) {
Log.e(TAG, "Failed to close socket trying to recover from SocketException", ioException);
}
}
}
}
客戶端測試代碼:
Socket socket = null;
SocketAddress addr = new InetSocketAddress(host, PORT);
int socketTOms = 5000;
try {
socket = new Socket(host, PORT);
socket.setKeepAlive(false);
String syncReq = "Request to server.";
//Send Request//
OutputStream outputStream = socket.getOutputStream();
outputStream.write(syncReq.getBytes());
socket.setSoTimeout(socketTOms);
//Rcv reply//
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i(TAG, "Message received! " + in.readLine());
} catch (SocketTimeoutException e) {
Log.e(TAG, "Timeout while reading from socket: timeout=" + socketTOms);
} catch (Exception e) {
Log.e(TAG, "Exception", e);
} finally {
if (socket != null && socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Exception while closing socket", e);
}
}
}
我通過Android Studio中運行兩個不同的設備服務器和客戶端,可以在日誌中看到服務器收到請求併發送回復,但客戶端始終爲throws
SocketTimeoutException
。我看到其他地方socket.setKeepAlive(false)
將解決這個問題,但它似乎沒有任何效果。
似乎很簡單,但我看不到我在這裏失蹤。
謝謝SháilèndraWregmi –