在Android中如何停止正在对瓦亭一个新的Socket线程在对、线程、Android、Socket

2023-09-06 05:46:53 作者:劳资是农村人

我正在开发,使用一个插座连接到服务器的软件;

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();

在客户端无法连接到线程不断达到超时,直到等待新的Socket返回服务器。

When the client does not connect to the server the Thread keeps waiting for the return of the new Socket until timeout is reached.

欲使用户能够取消该操作。我试着再打电话给 connectionThread.interrupt()当用户单击后退按钮。但线程继续运行。

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.

我可以让线程运行,直到新的Socket超时,但我认为这不是很好。

I could let the thread runs until the new Socket timeout, but I think that It's not very good.

推荐答案

不要使用新的Socket(serverAddress,口); 。相反,采用先创建一个新的socket 新的Socket(),然后用连接插座 Socket.connect() 。通过这种方式,你可以

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)为连接指定超时( SocketTimeoutException 将提高),以及

1) specify a timeout for the connection (SocketTimeoutException will be raised), and

2)使用从不同的线程取消该过程 Socket.close() SocketException 将提高)

2) cancel the process from a different thread using Socket.close() (SocketException will be raised).

下面是一个使用这种方法,您code片断:

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();