Reputation: 403
I am using an asyncTask which runs for every 1 sec. I must check a condition every 1 sec that the socket connection is available or not before asyncTask starts.
I used socket.isConnected() -> it always returning true.
How to do this.
Please help..
Upvotes: 1
Views: 5030
Reputation: 127
Once a connection is made, isConnected() will always return true.
To check if the connection is still alive, you can:
Use socket.getInputStream().read()
. This will block until either some data arrives or the connection closes in which case it will return -1
. Otherwise it will return the received byte. If you use socket.setSoTimeout(t)
and then call read()
, 3 things can happen:
a) The connection closes and read()
returns -1
;
b) Some data arrives and read()
returns the read byte.
c) read()
will block for t
miliseconds and throw SocketTimeoutException
which means no data was received and the connection is okay.
2. Use socket.getInetAddress().isReachable(int timeout)
.
Upvotes: 1
Reputation: 3189
Its too late but it may help someone else all you need to do is just check for your socket if it is not null and then in case if it is not null just disconnect your socket else create new socket and connect that
if(socket != null) {
socket.disconnect();
} else {
socket.createSocket();
socket.connect();
}
here create socket is method in which you can create your socket Hope it may help someone.
Upvotes: -1
Reputation: 1
public class CheckSocket extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... strings) {
try {
socket = new Socket("192.168.15.101", 23);
} catch (IOException e) {
e.printStackTrace();
}
if(socket.isConnected()){
Log.d(TAG, "doInBackground: connected");
}else {
Log.d(TAG, "doInBackground: not connected");
}
return null;
}
}
Upvotes: -1