4

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.

Alex F
  • 42,307
  • 41
  • 144
  • 212
  • That's not correct. It may take up to about seventy seconds *if the host doesn't respond at all*, which would only happen if there was a network discontinuity or a firewall in the way. If the host responds, you will get either a connection or a 'connection refused' within a second or two. – user207421 Oct 06 '12 at 04:21
  • Non-existing host is handled within 1-2 seconds. BTW, does your note help to solve the problem (which is already solved)? – Alex F Oct 06 '12 at 05:49

3 Answers3

5

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.
Community
  • 1
  • 1
Matt Wolfe
  • 8,924
  • 8
  • 60
  • 77
1

You have to create a socket first and then use below method in it.

Socket client=new Socket();   
client.connect(new InetSocketAddress(hostip,port_num),connection_time_out); 
Arpit Patel
  • 1,561
  • 13
  • 23
0

You can do this:

Socket soc = null;
while(soc == null){
    try{
        soc = new Socket("x.x.x.x", portNumber);
    }
    catch(Exception ex){
    }
}

Since:

socket.connect(remoteAddress, timeout)

Is notoriously unreliable, you could code your own version of timeout. The code I wrote, waits for a connection infinitely, but you can very easily introduce a timer.

Sreekanth
  • 293
  • 3
  • 6