私はAndroidには新しく、ソケットプログラミングには多少新しいです。私は2台のデバイスを持っていて、Android 5.1
を実行し、WiFiダイレクトに接続しています(関連性があるかどうかはわかりません)。サーバーがソケット上の要求をリッスンしてから、クライアントに返信します。Android WiFiのダイレクトクライアントソケットのタイムアウト
同様に、クライアントコードは要求を送信し、サーバーからの応答をリッスンします。サーバーは応答を送信していますが、クライアントはメッセージを受け取ることはなく、ソケットはタイムアウトします。
Serverテストコード:
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);
}
}
}
}
クライアントのテストコード:私はAndroidのメーカーを介して2つの異なるデバイス上のサーバーとクライアントを実行していることだし、ログに見ることができます
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);
}
}
}
サーバー要求を受信して応答を送信しますが、クライアントは常にthrows
SocketTimeoutException
です。私は、そのsocket.setKeepAlive(false)
が問題を解決するところを見ましたが、何の効果もないようです。
シンプルなようですが、私はここで何が欠けているのか分かりません。
ありがとうSháilèndraWregmi –