简体   繁体   English

Socket.close()在Socket.connect()期间无效

[英]Socket.close() have no effect during Socket.connect()

Using the default socket implementation on Windows, I was not able to find any effective method to stop Socket.connect() . 使用Windows上的默认套接字实现,我无法找到任何有效的方法来停止Socket.connect() This answer suggests Thread.interrupt() will not work, but Socket.close() will. 这个答案表明Thread.interrupt()不起作用,但Socket.close()会。 However, in my trial, the latter didn't work either. 但是,在我的审判中,后者也没有用。

My goal is to terminate the application quickly and cleanly (ie clean up work needs to be done after the socket termination). 我的目标是快速,干净地终止应用程序(即在套接字终止后需要完成清理工作)。 I do not want to use the timeout in Socket.connect() because the process can be killed before a reasonable timeout has expired. 我不想在Socket.connect()使用超时,因为可以在合理的超时到期之前终止进程。

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

Output: 输出:

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

You fork the thread and then the main thread is trying to make the connection to the remote server. 您分叉线程,然后主线程尝试连接到远程服务器。 The socket is not yet connected so I suspect s.close() does nothing on a socket that is not connected. 套接字尚未连接,所以我怀疑s.close()在没有连接的套接字上什么都不做。 It's hard to see what the INET socket implementation does here. 很难看出INET套接字实现在这里做了什么。 t.interrupt(); won't work because the connect(...) is not interruptible. 因为connect(...)不可中断,所以不起作用。

You could use the NIO SocketChannel.connect(...) which looks to be interruptible. 您可以使用看起来可以中断的NIO SocketChannel.connect(...) Maybe something like: 也许是这样的:

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

Not sure if that would help though. 不确定这是否会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM