在准备好读取的多个套接字中进行选择

在准备好读取的多个套接字中进行选择

本文介绍了在准备好读取的多个套接字中进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写服务器客户端应用程序。我有一个服务器,它拥有我从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:


  1. 每个接受的套接字都有专用线程。这是因为'常规'套接字I / O正在阻塞。您无法使用单个线程有选择地处理多个套接字。由于没有偷看功能,当您调用读取时,您将始终面临被阻止的风险。通过为每个有兴趣读取的套接字创建一个线程,阻塞读取不会阻止任何其他操作(线程)。

  2. 使用NIO。 NIO允许异步I / O操作,基本上就是你要求的 - 选择器

  1. 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).
  2. Use NIO. NIO allows for asynchronous I/O operations, and basically exactly what you asked for - a Selector.

如果您决定采用NIO方式,我建议您查看和。我发现它们比普通的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.

这篇关于在准备好读取的多个套接字中进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:32