问题
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 new 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.
回答1:
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();
来源:https://stackoverflow.com/questions/4891044/in-android-how-to-stop-a-thread-that-is-wating-for-a-new-socket