如何中断 ServerSocket accept() 方法? [英] How can I interrupt a ServerSocket accept() method?

查看:32
本文介绍了如何中断 ServerSocket accept() 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的主线程中,我有一个 while(listening) 循环,它在我的 ServerSocket 对象上调用 accept(),然后开始一个新的客户端线程并在接受新客户端时将其添加到集合中.

In my main thread I have a while(listening) loop which calls accept() on my ServerSocket object, then starts a new client thread and adds it to a Collection when a new client is accepted.

我还有一个管理线程,我想用它来发出命令,例如 'exit',这将导致所有客户端线程关闭、自行关闭并关闭主线程,通过监听 false.

I also have an Admin thread which I want to use to issue commands, like 'exit', which will cause all the client threads to be shut down, shut itself down, and shut down the main thread, by turning listening to false.

然而,while(listening) 循环中的 accept() 调用阻塞了,而且似乎没有任何方法可以中断它,所以 while条件无法再次检查,程序无法退出!

However, the accept() call in the while(listening) loop blocks, and there doesn't seem to be any way to interrupt it, so the while condition cannot be checked again and the program cannot exit!

有没有更好的方法来做到这一点?或者有什么方法可以中断阻塞方法?

Is there a better way to do this? Or some way to interrupt the blocking method?

推荐答案

您可以调用 close() 来自另一个线程,以及 accept() 调用将抛出 SocketException.

You can call close() from another thread, and the accept() call will throw a SocketException.

这篇关于如何中断 ServerSocket accept() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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