in my current project I’m using my smartphone as a server. The server is started when a special Card or Tag was detected via NFC. This is the part that works.
In order to achieve this I’m using an AsyncTask that gets started once the tag is scanned. The problem is now, that I am not able to stop the server when he is currently calling ServerSocket.accept(). Calling AsyncTask.cancel(true) does not stop the server while he is waiting for a connection request.
How would I go about this if I want to stop the server at some point?
Right now I’m quite clueless. My only idea was to set the timeout time for the serversocket resulting in a thrown exception. But that would mean polling ServerSocket.accept() which can’t be the only way going about this? If it is, that would be a rather poor solution in my eyes…
One way is that you can call close() on the ServerSocket from another thread, which will throw a SocketException in accept().
Another is to use the timeout that you were thinking about.
See the following posts for ideas on how to implement this :
How can I interrupt a ServerSocket accept() method?
Java Stop Server Thread
Close listening ServerSocket
Stop a socket from listening on accept
How to unblock a thread blocked on ServerSocket.accept()?