繁体   English   中英

套接字AsyncTask不会在代码中记录socket.isConnected值

[英]Socket AsyncTask does not log the socket.isConnected value in the code

我有以下代码,以便在android中执行异步任务以连接到套接字。

调用asynctask是

new SocketAsyncTask().execute("abc");

导入android.os.AsyncTask; 导入android.util.Log;

导入java.io.IOException; 导入java.net.Socket;

公共类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 successl”或“ Client connection not successl”。 我尝试调试它,但是它基本上做了一些奇怪的事情。 它在logcat中打印“ In socket”,但似乎没有在该断点处停止。

首先,记录isConnected()没有意义。 如果构造函数未引发异常,则说明套接字连接。 在测试时, isConnected()测试不可能为假。

这里的问题是您忽略了应该记录的异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM