中断连接插座 [英] Interrupt a connecting socket

查看:91
本文介绍了中断连接插座的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GUI,其中包含要连接的服务器列表。如果用户单击它连接到它的服务器。如果用户单击第二个服务器,它将断开第一个服务器并连接到第二个服务器。每个新连接都在一个新线程中运行,以便程序可以执行其他任务。

I have a GUI with a list of servers to connect to. If a user clicks a server it connects to it. If a user clicks a second server, it will disconnect the first and connect to the second. Each new connection runs in a new thread so that the program can perform other tasks.

但是,如果用户在第一个服务器仍然连接时单击第二个服务器,则有两个同时连接。

However, if a user clicks a second server while the first is still connecting, there are two simultaneous connections.

我正在使用此连接,而connect()是阻塞的行:

I'm connecting using this, and connect() is the line that blocks:

Socket socket = new Socket();
socket.connect(socketAddress, connectTimeout);

我想也许 Thread.currentThread()。interrupt(); 可以工作,但没有。

I thought maybe Thread.currentThread().interrupt(); would work, but didn't.

我是否需要稍微重构我的代码以便继续进行第一次连接,但是直接关闭它后?或者实际上有一种方法可以中断connect方法。

Do I have to restructure my code a bit so that it continues making the first connection, but closes it straight after? Or is there actually a way to interrupt the connect method.

推荐答案

如果你正在使用阻塞套接字实现,则中断线程赢了't'取消'或中断你的套接字连接。打破阻塞调用的唯一方法是关闭套接字。您可以在Runnable任务上公开一个方法(例如 cancel ),该方法关闭套接字并在用户尝试连接到第二个服务器时清理资源。

If you are using a blocking socket implementation, interrupting the thread won't 'cancel' or interrupt your socket connection. The only way of breaking out of the 'blocking call' is to 'close' the socket. You can expose a method on your Runnable tasks (e.g. cancel) which close the socket and clean up the resources when the user tries connecting to a second server.

如果你想要,你可以拥有查看我的一次性尝试,打断阻塞调用的线程。

If you want you can have a look at my throwaway attempt at interrupting threads which make blocking calls.

这篇关于中断连接插座的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆