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

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

问题描述

在我的主线程中,我有一个而(监听)循环,它在我的ServerSocket对象上调用 accept() ,然后启动一个新的客户端线程,并在接受新客户端时将其添加到Collection。

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.

我还有一个Admin线程,我想用它来发出命令,比如'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.

但是, accept()调用 while(监听)循环块,似乎没有任何中断它的方法,因此无法再次检查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天全站免登陆