Socket.close () do not act during Socket.connect ()

Using the default socket implementation on Windows, I could not find an effective stop method Socket.connect(). This answer suggests that Thread.interrupt()it will not work, but it Socket.close()will. However, in my court the latter did not work either.

My goal is to quickly and cleanly complete the application (i.e. do the cleanup job after the socket completes). I do not want to use a timeout in Socket.connect(), because the process can be killed before a reasonable timeout expires.

import java.net.InetSocketAddress;
import java.net.Socket;


public class ComTest {
    static Socket s;
    static Thread t;

    public static void main(String[] args) throws Exception {
        s = new Socket();
        InetSocketAddress addr = new InetSocketAddress("10.1.1.1", 11);
        p(addr);
        t = Thread.currentThread();
        (new Thread() {
            @Override
            public void run() {
                try {
                    sleep(4000);
                    p("Closing...");
                    s.close();
                    p("Closed");
                    t.interrupt();
                    p("Interrupted");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        s.connect(addr);
    }

    static void p(Object o) {
        System.out.println(o);
    }
}

Conclusion:

/10.1.1.1:11
Closing...
Closed
Interrupted
(A few seconds later)
Exception in thread "main" java.net.SocketException: Socket operation on nonsocket: connect
+5
source share
1 answer

, . , , s.close() , . , INET. t.interrupt(); , connect(...) .

NIO SocketChannel.connect(...), . , - :

SocketChannel sc = SocketChannel.open();
// this can be interrupted
boolean connected = sc.connect(t.address);

, .

+4

All Articles