连接到服务器的多个 Socket 客户端 [英] Multiple Socket client connecting to a server

查看:40
本文介绍了连接到服务器的多个 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.

推荐答案

您希望通过 I/O 完成端口 (IOCP).

You want to be using asynchronous I/O with an I/O Completion Port (IOCP).

一时难以解释,但任何需要支持大量并发套接字的 Windows 应用程序都应该使用 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.

IOCP 本质上是 Windows 提供的线程安全工作队列.您将完成数据包"排队到 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.

您还可以将多种支持重叠操作的句柄(例如套接字)与 IOCP 相关联.当您将句柄与 IOCP 关联时,诸如 WSARecv 之类的重叠操作将自动向关联的 IOCP 发送完成数据包.

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.

因此,本质上,您可以让一个线程处理所有 1000 个连接.每个套接字将被创建为一个重叠的套接字,然后与您的 IOCP 相关联.然后您可以在所有 1000 个套接字上调用 WSARecv 并等待完成数据包变得可用.当接收到数据时,操作系统将向关联的 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.

这篇关于连接到服务器的多个 Socket 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆