简体   繁体   中英

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

I have the following code in order to execute a asynchronous task in android in order to connect to a socket.

call to the asynctask is

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

import android.os.AsyncTask; import android.util.Log;

import java.io.IOException; import java.net.Socket;

public class SocketAsyncTask extends 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;
}

}

The output does print the "In socket" string however, it does not log either "Client connection successfull" or "Client connection not successfull". I tried debugging it but it basically does something weird. It prints the "In socket" in logcat but does not seem to stop at that breakpoint.

There no point in logging isConnected() in the first place. If the constructor didn't throw an exception, the socket is connected. The isConnected() test cannot possibly be false at the point where you're testing it.

The problem here is that you're ignoring the exception, which you should be logging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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