0123456789 0123456789 - 4 months ago 9
Android Question

Socket timeout and cancellation

I have the following code running in AsyncTask:

socket = new Socket(host, Integer.parseInt(port));

In the case when host name is correct, but there is no socket server listening on the port, this line may work several minutes before throwing exception. Can I set communication timeout? Also, is it possible to stop this process - currently it doesn't react to AsyncTask.cancel call.


Create the socket with the no parameters contructor like this:

socket = new Socket();

Then use

socket.connect(remoteAddress, timeout);

See http://developer.android.com/reference/java/net/Socket.html for more information.

-- Update --

I didn't notice originally that you asked about how to cancel the socket connection. While I'm not real familiar with socket programming it looks like you would do this:

  1. Call cancel on the asynctask as you seem to already have tried.
  2. Override/Implement onCancelled method for the async task. In the implementation, you will need to use your reference to the socket (make it a class instance variable), and call the close() method of the socket. Be sure to read up on closing a socket and make sure you're handling the exceptions for the input/output stream appropriately so your app doesn't crash. Checkout this question for more info on closing sockets.