使用Windows上的默认套接字实现,我无法找到任何有效的方法来停止Socket.connect(). This answer表明Thread.interrupt()不起作用,但Socket.close()会.但是,在我的审判中,后者也没有用.
我的目标是快速,干净地终止应用程序(即在套接字终止后需要完成清理工作).我不想在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);
}
}
输出:
/10.1.1.1:11
Closing...
Closed
Interrupted
(A few seconds later)
Exception in thread "main" java.net.SocketException: Socket operation on nonsocket: connect
最佳答案
原文链接:https://www.f2er.com/java/438305.html