In Android how to stop a thread that is wating for a new Socket
I'm developing a software that connects to a server using a Socket;
connectionThread = new Thread(new Runnable( ) {
public void run() {
InetAddress serverAddress = InetAddress.getByName(ip);
serverSocket = new Socket(serverAddress, port);
//do more stuff
}
});
connectionThread.start();
When the client does not connect to the server the Thread keeps waiting for the return of the n开发者_开发百科ew Socket until timeout is reached.
I want to enable the user to cancel that action. I tried then to call connectionThread.interrupt()
when the user clicks the back button. But the thread keeps running.
I could let the thread runs until the new Socket timeout, but I think that It's not very good.
Don't use new Socket(serverAddress, port);
. Instead, first create a new socket using new Socket()
, and then connect the socket using Socket.connect()
. This way, you can
1) specify a timeout for the connection (SocketTimeoutException
will be raised), and
2) cancel the process from a different thread using Socket.close()
(SocketException
will be raised).
Here is your code snippet using this method:
connectionThread = new Thread(new Runnable( ) {
public void run() {
try {
InetAddress serverAddress = InetAddress.getByName(ip);
serverSocket = new Socket();
serverSocket.connect(new InetSocketAddress(serverAddress,port),TIMEOUTMS);
//do more stuff
} catch (SocketTimeoutException ste)
{
// connect() timeout occurred
} catch (SocketException se)
{
// socket exception during connect (e.g. socket.close() called)
}
}});
connectionThread.start();
精彩评论