Ping the server without freezing the stream
I tried to use multiple threads, unfortunately no luck:
public synchronized boolean pingServer(final String ip, final short port) {
final boolean[] returnbol = new boolean[1];
Thread tt = new Thread(new Runnable() {
@Override
public void run() {
try {
Socket s = new Socket(ip, port);
s.close();
returnbol[0] = true;
} catch (IOException e) {
returnbol[0] = false;
}
}
});
tt.start();
try {
tt.join();
} catch (InterruptedException e) {
tt.stop();
}
tt.stop();
return returnbol[0];
}
The main thread still hangs for some reason.
Is there a "bleak" way to ping a server?
+3
source to share
2 answers
What exactly did you want to get in
try {
tt.join();
} catch (InterruptedException e) {
tt.stop();
}
block? Here you are connected to a parallel thread and you are waiting for that thread to end (receiving a ping result).
You have the following options:
- Wait for the ping to finish.
- Don't wait ... and didn't get the result.
- Use some concurrency classes like Future <> to get the result (but you will block the thread the moment you ask for the result if you haven't got it already)
- Or you can use the "callback" function / interface to output the result from the internal "ping" stream.
+3
source to share