Ad

How To Tell If The Server Socket Is Not Available?

- 1 answer

socket client is running on android:

try {
    socketClient = new Socket(host, port);

    //set socket input
    in = socketClient.getInputStream();
    dIn = new DataInputStream(in);

    //set socket output
    out = socketClient.getOutputStream();
    dOut = new DataOutputStream(out);

    int c = 0;
    String data = "";

    while ((c = dIn.read()) != -1) {
       //print data
    }
} catch (Exception e) {
    //close connection
}

my server run on python and everything is works fine except until the server is not running and when i try to connect to server it takes two minutes to catch the error that the server is not available
How can I reduce the time for example catch the error in 10 sec

Ad

Answer

According to this answer

use

Socket socketClient = new Socket();   
socketClient.connect(new InetSocketAddress(host, port),connection_time_out)

instead of

socketClient = new Socket(host, port);

connection_time_out = limits the time allowed to establish a connection in the case that the connection is refused or server doesn't exist.

Ad
source: stackoverflow.com
Ad