我有以下代码,以便在 android 中执行异步任务以连接到套接字。
调用异步任务是
new SocketAsyncTask().execute("abc");
导入android.os.AsyncTask; 导入 android.util.Log;
导入java.io.IOException; 导入java.net.Socket;
公共(public)类 SocketAsyncTask 扩展 AsyncTask {
private static String connectionURL ="MY_URL" ;
private static int port = 3000;
@Override
protected Void doInBackground(String... uri) {
try {
String sentence;
String modifiedSentence;
Socket clientSocket = new Socket(connectionURL, port);
Log.d("In socket",clientSocket.isConnected() + "");
if (clientSocket.isConnected()) {
Log.d("Client connection Successfull!!", "true");
//System.out.print("Connection Successfull!!");
} else {
//System.out.print("Connection Not Successfull!!");
Log.d("Client connection not Successfull!!", "true");
}
/*DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);*/
clientSocket.close();
}catch (IOException exp) {
}
return null;
}
输出确实会打印“In socket”字符串,但是它不会记录“Client connection successfull”或“Client connection not successfull”。我尝试调试它,但它基本上做了一些奇怪的事情。它在 logcat 中打印“In socket”,但似乎并没有在该断点处停止。
最佳答案
首先记录 isConnected()
是没有意义的。如果构造函数没有抛出异常,则套接字已 已连接。 isConnected()
测试不可能在您测试时为假。
这里的问题是您忽略了应该记录的异常。
关于java - Socket AsyncTask 不会在代码中记录 socket.isConnected 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31193818/