在Android中如何停止正在等待新套接字的线程
我正在开发一个使用 Socket 连接到服务器的软件;
connectionThread = new Thread(new Runnable( ) {
public void run() {
InetAddress serverAddress = InetAddress.getByName(ip);
serverSocket = new Socket(serverAddress, port);
//do more stuff
}
});
connectionThread.start();
当客户端没有连接到服务器时,线程将继续等待新套接字的返回,直到达到超时。
我想让用户取消该操作。然后,我尝试在用户单击后退按钮时调用 connectionThread.interrupt()
。但线程仍在运行。
我可以让线程运行直到新的 Socket 超时,但我认为这不是很好。
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();
When the client does not connect to the server the Thread keeps waiting for the return of the new Socket until timeout is reached.
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.
I could let the thread runs until the new Socket timeout, but I think that It's not very good.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要使用
new Socket(serverAddress, port);
。相反,首先使用new Socket()
创建一个新套接字,然后使用Socket.connect()
连接该套接字。这样,您可以1) 指定连接超时(将引发 SocketTimeoutException),
2) 使用 Socket.close() 从不同线程取消进程(将引发
SocketException
)。这是使用此方法的代码片段:
Don't use
new Socket(serverAddress, port);
. Instead, first create a new socket usingnew Socket()
, and then connect the socket usingSocket.connect()
. This way, you can1) specify a timeout for the connection (
SocketTimeoutException
will be raised), and2) cancel the process from a different thread using
Socket.close()
(SocketException
will be raised).Here is your code snippet using this method: