在多个可供读取的套接字中进行选择
我正在编写一个服务器客户端应用程序。我有一个服务器,其中包含从 ServerSocket 的accept() 方法获得的多个套接字。我想从这些套接字读取数据,但我不一定知道哪个套接字已准备好读取。我需要某种选择器来选择一个准备好读取的套接字,这样我就可以读取它发送的数据。
谢谢。
I am writing a server-client application. I have a server that holds several sockets that I have got from the accept() method of ServerSocket. I want to read from these sockets but I don't necesserally know which socket is ready to be read from. I need some kind of selector that will select one of the sockets that are ready to be read from, so I can read the data it sends.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上有两个选项可以使其工作:
read
时,您始终会面临被阻止的风险。通过让您感兴趣的每个套接字都有一个线程,阻塞读取不会阻塞任何其他操作(线程)。如果您确实决定采用 NIO 方式,我建议您查看 MINA 和 Netty。我发现它们比普通的 NIO 更容易使用。您不仅会获得更好的 API 来使用,而且至少 MINA 还针对一些令人讨厌的 NIO 错误提供了解决方法。
You have basically two options to make it work:
read
. By having a thread per each socket you are interested in reading, blocking reads will not block any other operations (threads).If you do decide to go NIO-way, I would recommend checking out MINA and Netty. I've found them much easier to work with than plain NIO. Not only will you get a nicer API to work with, but at least MINA had workarounds for some nasty NIO bugs, too.