In Android how to stop a thread that is wating for a new Socket

北城余情 提交于 2020-02-22 13:03:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!