我有一个应用程序需要读取数百个套接字通信。
我正在使用具有线程数量上限的线程池来为这些套接字提供服务。如果套接字没有传入消息,这会导致所有线程阻塞。
我目前使用 100 毫秒的 soTimeout 来避免永久阻塞。我不喜欢这种方法,因为它可能会在开始接收输入时超时。
还有其他方法可以解决这个问题吗?
我尝试使用 ObjectInputStream.isAvailable() 检查,但无论流中是否有数据,它总是返回 0。
我找不到任何其他方法来检查流上是否有数据。这将是理想的,因为这样我可以检查是否有数据,如果没有,则继续到下一个流。
I have an application that needs to read hundreds of socket communications.
I am using a ThreadPool, with a upper limit on the number of threads, to service these sockets. This causes blocking on all threads if the sockets do not have incoming messages.
I am currently using a soTimeout of 100ms to avoid a permanent blocking. I do not like this approach as it might timeout just as it starts receiving input.
Is there anyway other to approach this?
I tried checking with ObjectInputStream.isAvailable(), but that always returns 0, whether there is data in the stream or not.
I can't find any other way to check whether there is data on the stream. This would be ideal, as then I could check if there is data, if not then move on to next stream.
发布评论
评论(2)
这正是 NIO 框架要解决的问题。不幸的是,使用原始 NIO 比使用阻塞 IO 更困难一些。如果可以的话,我的建议是尝试 像 Netty 这样的框架,这会减轻你的工作负担。
This is exactly the kind of problem NIO frameworks are meant to solve. Unfortunately, using raw NIO is a bit more difficult than using blocking IO. If you can, my recommendation would be to try out a framework like Netty which would ease the job for you.
你可以给蔚来一个机会。
使用Selector和SocketChannels来等待数据,而不是为每个套接字创建线程。
选择器
SocketChannel
You can give NIO a chance.
Use Selector and SocketChannels to wait for data instead of creating thread for each socket.
Selector
SocketChannel