在准备好从中读取的多个套接字中进行选择 [英] selecting among multiple sockets that are ready to be read from
问题描述
我正在编写一个服务器-客户端应用程序.我有一个服务器,其中包含我从 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.
谢谢.
推荐答案
基本上有两个选项可以使它工作:
You have basically two options to make it work:
- 每个接受的套接字都有专用线程.这是因为常规"套接字 I/O 正在阻塞.您不能使用单个线程有选择地处理多个套接字.由于没有窥视"功能,当您调用
read
时,您将始终面临被阻止的风险.通过为您感兴趣的每个套接字设置一个线程,阻塞读取不会阻塞任何其他操作(线程). - 使用蔚来.NIO 允许异步 I/O 操作,基本上正是您所要求的 - Selector.
- Have dedicated thread per accepted socket. This is because the 'regular' socket I/O is blocking. You can not selectively handle multiple sockets using a single thread. And as there is no 'peeking' functionality, you will always take a risk of getting blocked when you invoke
read
. By having a thread per each socket you are interested in reading, blocking reads will not block any other operations (threads). - Use NIO. NIO allows for asynchronous I/O operations, and basically exactly what you asked for - a Selector.
如果您决定采用 NIO 方式,我建议您查看 MINA 和 Netty.我发现它们比普通的 NIO 更容易使用.您不仅会获得更好的 API 来使用,而且至少 MINA 也有解决一些讨厌的 NIO 错误的方法.
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.
这篇关于在准备好从中读取的多个套接字中进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!