多个 Socket 客户端连接到服务器
我正在设计一个模拟器应用程序,其中应用程序启动到服务器的多个套接字连接(大约 1000 个连接)。我不想启动那么多线程来处理这些连接,因为系统无法处理那么多客户端。使用 Select 没有意义,因为我需要循环 1000 个连接,这可能会很慢。请建议我如何处理这种情况。
I am designing an simulator application where the application launches multiple socket connection(around 1000 connections) to a server. I don't want to launch as many as threads to handle those connections, since the system cant handle that much clients. Using Select doesnt make sense, since i need to loop through 1000 connections which may be slow. Please suggest me how to handle this scenario.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您希望将异步 I/O 与 结合使用I/O 完成端口 (IOCP)。
暂时无法解释太多内容,但任何需要支持大量并发套接字的 Windows 应用程序都应该使用 IOCP。
IOCP本质上是Windows提供的线程安全工作队列。您将“完成数据包”排队到 IOCP,然后另一个线程将其出列并处理它。
您还可以将支持重叠操作的多种类型的句柄(例如套接字)关联到 IOCP。当您将句柄与 IOCP 关联时,诸如 WSARecv 之类的重叠操作将自动向关联的 IOCP 发送完成数据包。
因此,本质上,您可以让一个线程处理所有 1000 个连接。每个套接字将被创建为重叠套接字,然后与您的 IOCP 关联。然后,您可以在所有 1000 个套接字上调用
WSARecv
并等待完成数据包可用。当接收到数据时,操作系统将向关联的 IOCP 发送一个完成数据包。这将包含相关信息,例如读取了多少数据以及包含数据的缓冲区。You want to be using asynchronous I/O with an I/O Completion Port (IOCP).
It's too much to explain shortly, but any Windows application that needs to support a large number of concurrent sockets should be using an IOCP.
An IOCP is essentially an Windows-provided thread safe work queue. You queue a 'completion packet' to an IOCP and then another thread dequeues it and does work with it.
You can also associate many types of handles that support overlapped operations, such as sockets, to an IOCP. When you associate a handle with an IOCP, overlapped operations such as
WSARecv
will automatically post a completion packet to the associated IOCP.So, essentially, you could have one thread handling all 1000 connections. Each socket will be created as an overlapped socket and then associated with your IOCP. You can then call
WSARecv
on all 1000 sockets and wait for a completion packet to become available. When data is received, the operating system will post a completion packet to the associated IOCP. This will contain relevant information, such as how much data was read and the buffer containing the data.循环 1000 个句柄仍然比发送 1000 个数据包快得多,因此我不担心这里的性能。
select()
仍然是要走的路。Looping through 1000 handles is still significantly faster than sending 1000 packets, so I wouldn't worry about performance here.
select()
is still the way to go.