DreamWorks

Never say Never。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C++之Socket I/O五种模型

Posted on 2013-07-29 20:46  _Babyface  阅读(723)  评论(0编辑  收藏  举报
  1 //我们假设客户端的代码如下(为代码直观,省去所有错误检查,以下同):
  2 #include <WINSOCK2.H>
  3 #include <stdio.h>
  4 #define SERVER_ADDRESS "137.117.2.148"
  5 #define PORT           5150
  6 #define MSGSIZE        1024
  7 #pragma comment(lib, "ws2_32.lib")
  8 int main()
  9 {
 10   WSADATA     wsaData;
 11   SOCKET      sClient;
 12   SOCKADDR_IN server;
 13   char        szMessage[MSGSIZE];
 14   int         ret;
 15   
 16   // Initialize Windows socket library
 17   WSAStartup(0x0202, &wsaData);
 18   // Create client socket
 19   sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 20   // Connect to server
 21   memset(&server, 0, sizeof(SOCKADDR_IN));
 22   server.sin_family = AF_INET;
 23   server.sin_addr.S_un.S_addr = inet_addr(SERVER_ADDRESS);
 24   server.sin_port = htons(PORT);
 25   connect(sClient, (struct sockaddr *)&server, sizeof(SOCKADDR_IN));
 26   while (TRUE)
 27   {
 28     printf("Send:");
 29   gets(szMessage);
 30     // Send message
 31     send(sClient, szMessage, strlen(szMessage), 0);
 32     // Receive message
 33     ret = recv(sClient, szMessage, MSGSIZE, 0);
 34     szMessage[ret] = '\0';
 35     printf("Received [%d bytes]: '%s'\n", ret, szMessage);
 36   }
 37   // Clean up
 38   closesocket(sClient);
 39   WSACleanup();
 40   return 0;
 41 }
 42 /*客户端所做的事情相当简单,创建套接字,连接服务器,然后不停的发送和接收数据。比较容易想到的一种服务器模型就是采用一个主线程,负责监听客户端的连接请求,当接收到某个客户端的连接请求后,创建一个专门用于和该客户端通信的套接字和一个辅助线程。以后该客户端和服务器的交互都在这个辅助线程内完成。这种方法比较直观,程序非常简单而且可移植性好,但是不能利用平台相关的特性。例如,如果连接数增多的时候(成千上万的连接),那么线程数成倍增长,操作系统忙于频繁的线程间切换,而且大部分线程在其生命周期内都是处于非活动状态的,这大大浪费了系统的资源。所以,如果你已经知道你的代码只会运行在Windows平台上,建议采用Winsock I/O模型。
 43 一.选择模型
 44 Select(选择)模型是Winsock中最常见的I/O模型。之所以称其为“Select模型”,是由于它的“中心思想”便是利用select函数,实现对I/O的管理。最初设计该模型时,主要面向的是某些使用UNIX操作系统的计算机,它们采用的是Berkeley套接字方案。Select模型已集成到Winsock 1.1中,它使那些想避免在套接字调用过程中被无辜“锁定”的应用程序,采取一种有序的方式,同时进行对多个套接字的管理。由于Winsock 1.1向后兼容于Berkeley套接字实施方案,所以假如有一个Berkeley套接字应用使用了select函数,那么从理论角度讲,毋需对其进行任何修改,便可正常运行。
 45 下面的这段程序就是利用选择模型实现的Echo服务器的代码(已经不能再精简了):
 46 */
 47 #include <winsock.h>
 48 #include <stdio.h>
 49 #define PORT       5150
 50 #define MSGSIZE    1024
 51 #pragma comment(lib, "ws2_32.lib")
 52 int    g_iTotalConn = 0;
 53 SOCKET g_CliSocketArr[FD_SETSIZE];
 54 DWORD WINAPI WorkerThread(LPVOID lpParameter);
 55 int main()
 56 {
 57   WSADATA     wsaData;
 58   SOCKET      sListen, sClient;
 59   SOCKADDR_IN local, client;
 60   int         iaddrSize = sizeof(SOCKADDR_IN);
 61   DWORD       dwThreadId;
 62   // Initialize Windows socket library
 63   WSAStartup(0x0202, &wsaData);
 64   // Create listening socket
 65   sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 66   // Bind
 67   local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
 68   local.sin_family = AF_INET;
 69   local.sin_port = htons(PORT);
 70   bind(sListen, (struct sockaddr *)&local, sizeof(SOCKADDR_IN));
 71   // Listen
 72   listen(sListen, 3);
 73   // Create worker thread
 74   CreateThread(NULL, 0, WorkerThread, NULL, 0, &dwThreadId);  
 75   while (TRUE)
 76   {
 77     // Accept a connection
 78     sClient = accept(sListen, (struct sockaddr *)&client, &iaddrSize);
 79     printf("Accepted client:%s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
 80     // Add socket to g_CliSocketArr
 81     g_CliSocketArr[g_iTotalConn++] = sClient;
 82   }
 83   
 84   return 0;
 85 }
 86 DWORD WINAPI WorkerThread(LPVOID lpParam)
 87 {
 88   int            i;
 89   fd_set         fdread;
 90   int            ret;
 91   struct timeval tv = {1, 0};
 92   char           szMessage[MSGSIZE];
 93   
 94   while (TRUE)
 95   {
 96     FD_ZERO(&fdread);
 97     for (i = 0; i < g_iTotalConn; i++)
 98     {
 99       FD_SET(g_CliSocketArr, &fdread);
100     }
101     // We only care read event
102     ret = select(0, &fdread, NULL, NULL, &tv);
103     if (ret == 0)
104     {
105       // Time expired
106       continue;
107     }
108     for (i = 0; i < g_iTotalConn; i++)
109     {
110       if (FD_ISSET(g_CliSocketArr, &fdread))
111       {
112         // A read event happened on g_CliSocketArr
113         ret = recv(g_CliSocketArr, szMessage, MSGSIZE, 0);
114         if (ret == 0 || (ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET))
115         {
116             // Client socket closed
117             printf("Client socket %d closed.\n", g_CliSocketArr);
118             closesocket(g_CliSocketArr);
119             if (i < g_iTotalConn - 1)
120             {            
121                 g_CliSocketArr[i--] = g_CliSocketArr[--g_iTotalConn];
122             }
123         }
124         else
125         {
126             // We received a message from client
127             szMessage[ret] = '\0';
128             send(g_CliSocketArr, szMessage, strlen(szMessage), 0);
129         }
130      }
131    }
132  }
133   return 0;
134 }
135 /*服务器的几个主要动作如下:
136 1.创建监听套接字,绑定,监听;
137 2.创建工作者线程;
138 3.创建一个套接字数组,用来存放当前所有活动的客户端套接字,每accept一个连接就更新一次数组;
139 4.接受客户端的连接。这里有一点需要注意的,就是我没有重新定义FD_SETSIZE宏,所以服务器最多支持的并发连接数为64。而且,这里决不能无条件的accept,服务器应该根据当前的连接数来决定是否接受来自某个客户端的连接。一种比较好的实现方案就是采用WSAAccept函数,而且让WSAAccept回调自己
140 实现的Condition Function。如下所示:
141 */
142 int CALLBACK ConditionFunc(LPWSABUF lpCallerId,LPWSABUF lpCallerData, 
143             LPQOS lpSQOS,LPQOS lpGQOS,LPWSABUF lpCalleeId, LPWSABUF lpCalleeData,GROUP FAR * g,DWORD dwCallbackData)
144 {
145 if (当前连接数 < FD_SETSIZE)
146   return CF_ACCEPT;
147 else
148   return CF_REJECT;
149 }
150 /*工作者线程里面是一个死循环,一次循环完成的动作是:
151 1.将当前所有的客户端套接字加入到读集fdread中;
152 2.调用select函数;
153 3.查看某个套接字是否仍然处于读集中,如果是,则接收数据。如果接收的数据长度为0,或者发生WSAECONNRESET错误,则表示客户端套接字主动关闭,这时需要将服务器中对应的套接字所绑定的资源释放掉,然后调整我们的套接字数组(将数组中最后一个套接字挪到当前的位置上)除了需要有条件接受客户端的连接外,还需要在连接数为0的情形下做特殊处理,因为如果读集中没有任何套接字,select函数会立刻返回,这将导致工作者线程成为一个毫无停顿的死循环,CPU的占用率马上达到100%。
154 二.异步选择
155 Winsock提供了一个有用的异步I/O模型。利用这个模型,应用程序可在一个套接字上,接收以Windows消息为基础的网络事件通知。具体的做法是在建好一个套接字后,调用WSAAsyncSelect函数。该模型最早出现于Winsock的1.1版本中,用于帮助应用程序开发者面向一些早期的16位Windows平台(如Windows for Workgroups),适应其“落后”的多任务消息环境。应用程序仍可从这种模型中得到好处,特别是它们用一个标准的Windows例程(常称为"WndProc"),对窗口消息进行管理的时候。该模型亦得到了Microsoft Foundation Class(微软基本类,MFC)对象CSocket的采纳。
156 我还是先贴出代码,然后做详细解释:
157 */
158 #include <winsock.h>
159 #include <tchar.h>
160 #define PORT      5150
161 #define MSGSIZE   1024
162 #define WM_SOCKET WM_USER+0
163 #pragma comment(lib, "ws2_32.lib")
164 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
165 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
166 {
167   static TCHAR szAppName[] = _T("AsyncSelect Model");
168   HWND         hwnd ;
169   MSG          msg ;
170   WNDCLASS     wndclass ;
171   wndclass.style         = CS_HREDRAW | CS_VREDRAW ;
172   wndclass.lpfnWndProc   = WndProc ;
173   wndclass.cbClsExtra    = 0 ;
174   wndclass.cbWndExtra    = 0 ;
175   wndclass.hInstance     = hInstance ;
176   wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
177   wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
178   wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
179   wndclass.lpszMenuName  = NULL ;
180   wndclass.lpszClassName = szAppName ;
181   if (!RegisterClass(&wndclass))
182   {
183     MessageBox (NULL, TEXT ("This program requires Windows NT!"), szAppName, MB_ICONERROR) ;
184     return 0 ;
185   }
186   hwnd = CreateWindow (szAppName,                  // window class name
187                        TEXT ("AsyncSelect Model"), // window caption
188                        WS_OVERLAPPEDWINDOW,        // window style
189                        CW_USEDEFAULT,              // initial x position
190                        CW_USEDEFAULT,              // initial y position
191                        CW_USEDEFAULT,              // initial x size
192                        CW_USEDEFAULT,              // initial y size
193                        NULL,                       // parent window handle
194                        NULL,                       // window menu handle
195                        hInstance,                  // program instance handle
196                        NULL) ;                     // creation parameters
197   ShowWindow(hwnd, iCmdShow);
198   UpdateWindow(hwnd);
199   while (GetMessage(&msg, NULL, 0, 0))
200   {
201     TranslateMessage(&msg) ;
202     DispatchMessage(&msg) ;
203   }
204   
205   return msg.wParam;
206 }
207 LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
208 {
209   WSADATA       wsd;
210   static SOCKET sListen;
211   SOCKET        sClient;
212   SOCKADDR_IN   local, client;
213   int           ret, iAddrSize = sizeof(client);
214   char          szMessage[MSGSIZE];
215   switch (message)
216   {
217 case WM_CREATE:
218     // Initialize Windows Socket library
219   WSAStartup(0x0202, &wsd);
220   
221   // Create listening socket
222     sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
223     
224   // Bind
225     local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
226   local.sin_family = AF_INET;
227   local.sin_port = htons(PORT);
228   bind(sListen, (struct sockaddr *)&local, sizeof(local));
229   
230   // Listen
231     listen(sListen, 3);
232     // Associate listening socket with FD_ACCEPT event
233   WSAAsyncSelect(sListen, hwnd, WM_SOCKET, FD_ACCEPT);
234   return 0;
235   case WM_DESTROY:
236     closesocket(sListen);
237     WSACleanup();
238     PostQuitMessage(0);
239     return 0;
240   
241   case WM_SOCKET:
242     if (WSAGETSELECTERROR(lParam))
243     {
244       closesocket(wParam);
245       break;
246     }
247     
248     switch (WSAGETSELECTEVENT(lParam))
249     {
250     case FD_ACCEPT:
251       // Accept a connection from client
252       sClient = accept(wParam, (struct sockaddr *)&client, &iAddrSize);
253       
254       // Associate client socket with FD_READ and FD_CLOSE event
255       WSAAsyncSelect(sClient, hwnd, WM_SOCKET, FD_READ | FD_CLOSE);
256       break;
257     case FD_READ:
258       ret = recv(wParam, szMessage, MSGSIZE, 0);
259       if (ret == 0 || ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET)
260       {
261         closesocket(wParam);
262       }
263       else
264       {
265         szMessage[ret] = '\0';
266         send(wParam, szMessage, strlen(szMessage), 0);
267       }
268       break;
269       
270     case FD_CLOSE:
271       closesocket(wParam);      
272       break;
273     }
274     return 0;
275   }
276   
277   return DefWindowProc(hwnd, message, wParam, lParam);
278 }
279 
280 /*在我看来,WSAAsyncSelect是最简单的一种Winsock I/O模型(之所以说它简单是因为一个主线程就搞定了)。使用Raw Windows API写过窗口类应用程序的人应该都能看得懂。这里,我们需要做的仅仅是:
281 1.在WM_CREATE消息处理函数中,初始化Windows Socket library,创建监听套接字,绑定,监听,并且调用WSAAsyncSelect函数表示我们关心在监听套接字上发生的FD_ACCEPT事件;
282 2.自定义一个消息WM_SOCKET,一旦在我们所关心的套接字(监听套接字和客户端套接字)上发生了某个事件,系统就会调用WndProc并且message参数被设置为WM_SOCKET;
283 3.在WM_SOCKET的消息处理函数中,分别对FD_ACCEPT、FD_READ和FD_CLOSE事件进行处理;
284 4.在窗口销毁消息(WM_DESTROY)的处理函数中,我们关闭监听套接字,清除Windows Socket library下面这张用于WSAAsyncSelect函数的网络事件类型表可以让你对各个网络事件有更清楚的认识:
285 表1
286 FD_READ 应用程序想要接收有关是否可读的通知,以便读入数据 
287 FD_WRITE 应用程序想要接收有关是否可写的通知,以便写入数据 
288 FD_OOB 应用程序想接收是否有带外(OOB)数据抵达的通知 
289 FD_ACCEPT 应用程序想接收与进入连接有关的通知 
290 FD_CONNECT 应用程序想接收与一次连接或者多点join操作完成的通知 
291 FD_CLOSE 应用程序想接收与套接字关闭有关的通知 
292 FD_QOS 应用程序想接收套接字“服务质量”(QoS)发生更改的通知 
293 FD_GROUP_QOS  应用程序想接收套接字组“服务质量”发生更改的通知(现在没什么用处,为未来套接字组的使用保留) 
294 FD_ROUTING_INTERFACE_CHANGE 应用程序想接收在指定的方向上,与路由接口发生变化的通知 
295 FD_ADDRESS_LIST_CHANGE  应用程序想接收针对套接字的协议家族,本地地址列表发生变化的通知 
296 三.事件选择
297 Winsock提供了另一个有用的异步I/O模型。和WSAAsyncSelect模型类似的是,它也允许应用程序在一个或多个套接字上,接收以事件为基础的网络事件通知。对于表1总结的、由WSAAsyncSelect模型采用的网络事件来说,它们均可原封不动地移植到新模型。在用新模型开发的应用程序中,也能接收和处理所有那些事件。该模型最主要的差别在于网络事件会投递至一个事件对象句柄,而非投递至一个窗口例程。
298 还是让我们先看代码然后进行分析:
299 */
300 #include <winsock2.h>
301 #include <stdio.h>
302 #define PORT    5150
303 #define MSGSIZE 1024
304 #pragma comment(lib, "ws2_32.lib")
305 int      g_iTotalConn = 0;
306 SOCKET   g_CliSocketArr[MAXIMUM_WAIT_OBJECTS];
307 WSAEVENT g_CliEventArr[MAXIMUM_WAIT_OBJECTS];
308 DWORD WINAPI WorkerThread(LPVOID);
309 void Cleanup(int index);
310 int main()
311 {
312   WSADATA     wsaData;
313   SOCKET      sListen, sClient;
314   SOCKADDR_IN local, client;
315   DWORD       dwThreadId;
316   int         iaddrSize = sizeof(SOCKADDR_IN);
317   // Initialize Windows Socket library
318   WSAStartup(0x0202, &wsaData);
319   // Create listening socket
320   sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
321   // Bind
322   local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
323 local.sin_family = AF_INET;
324 local.sin_port = htons(PORT);
325   bind(sListen, (struct sockaddr *)&local, sizeof(SOCKADDR_IN));
326   // Listen
327   listen(sListen, 3);
328   // Create worker thread
329   CreateThread(NULL, 0, WorkerThread, NULL, 0, &dwThreadId);
330   while (TRUE)
331   {
332     // Accept a connection
333     sClient = accept(sListen, (struct sockaddr *)&client, &iaddrSize);
334     printf("Accepted client:%s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
335     // Associate socket with network event
336     g_CliSocketArr[g_iTotalConn] = sClient;
337     g_CliEventArr[g_iTotalConn] = WSACreateEvent();
338     WSAEventSelect(g_CliSocketArr[g_iTotalConn],
339                    g_CliEventArr[g_iTotalConn],
340                    FD_READ | FD_CLOSE);
341     g_iTotalConn++;
342   }
343 }
344 DWORD WINAPI WorkerThread(LPVOID lpParam)
345 {
346   int              ret, index;
347   WSANETWORKEVENTS NetworkEvents;
348   char             szMessage[MSGSIZE];
349   while (TRUE)
350   {
351     ret = WSAWaitForMultipleEvents(g_iTotalConn, g_CliEventArr, FALSE, 1000, FALSE);
352     if (ret == WSA_WAIT_FAILED || ret == WSA_WAIT_TIMEOUT)
353     {
354       continue;
355     }
356     index = ret - WSA_WAIT_EVENT_0;
357     WSAEnumNetworkEvents(g_CliSocketArr[index], g_CliEventArr[index], &NetworkEvents);
358     if (NetworkEvents.lNetworkEvents & FD_READ)
359     {
360       // Receive message from client
361       ret = recv(g_CliSocketArr[index], szMessage, MSGSIZE, 0);
362       if (ret == 0 || (ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET))
363       {
364         Cleanup(index);
365       }
366       else
367       {
368         szMessage[ret] = '\0';
369         send(g_CliSocketArr[index], szMessage, strlen(szMessage), 0);
370       }
371     }
372     if (NetworkEvents.lNetworkEvents & FD_CLOSE)
373   {
374    Cleanup(index);
375   }
376   }
377   return 0;
378 }
379 void Cleanup(int index)
380 {
381   closesocket(g_CliSocketArr[index]);
382 WSACloseEvent(g_CliEventArr[index]);
383 if (index < g_iTotalConn - 1)
384 {
385   g_CliSocketArr[index] = g_CliSocketArr[g_iTotalConn - 1];
386   g_CliEventArr[index] = g_CliEventArr[g_iTotalConn - 1];
387 }
388 
389 g_iTotalConn--;
390 }
391 
392 /*事件选择模型也比较简单,实现起来也不是太复杂,它的基本思想是将每个套接字都和一个WSAEVENT对象对应起来,
393 并且在关联的时候指定需要关注的哪些网络事件。一旦在某个套接字上发生了我们关注的事件(FD_READ和FD_CLOSE),与之相关联的WSAEVENT对象被Signaled。程序定义了两个全局数组,一个套接字数组,一个WSAEVENT对象数组,其大小都是MAXIMUM_WAIT_OBJECTS(64),两个数组中的元素一一对应。
394 同样的,这里的程序没有考虑两个问题,一是不能无条件的调用accept,因为我们支持的并发连接数有限。
395 解决方法是将套接字按MAXIMUM_WAIT_OBJECTS分组,每MAXIMUM_WAIT_OBJECTS个套接字一组,每一组分配一个
396 工作者线程;或者采用WSAAccept代替accept,并回调自己定义的Condition Function。第二个问题是没有对连接数
397 为0的情形做特殊处理,程序在连接数为0的时候CPU占用率为100%。
398 四.重叠I/O模型
399 Winsock2的发布使得Socket I/O有了和文件I/O统一的接口。我们可以通过使用Win32文件操纵函数ReadFile和
400 WriteFile来进行Socket I/O。伴随而来的,用于普通文件I/O的重叠I/O模型和完成端口模型对Socket I/O也适用了。
401 这些模型的优点是可以达到更佳的系统性能,但是实现较为复杂,里面涉及较多的C语言技巧。例如我们在完成端口
402 模型中会经常用到所谓的“尾随数据”。
403 1.用事件通知方式实现的重叠I/O模型
404 */
405 #include <winsock2.h>
406 #include <stdio.h>
407 #define PORT    5150
408 #define MSGSIZE 1024
409 #pragma comment(lib, "ws2_32.lib")
410 typedef struct
411 {
412   WSAOVERLAPPED overlap;
413   WSABUF        Buffer;
414   char          szMessage[MSGSIZE];
415   DWORD         NumberOfBytesRecvd;
416   DWORD         Flags;
417 }PER_IO_OPERATION_DATA, *LPPER_IO_OPERATION_DATA;
418 int                     g_iTotalConn = 0;
419 SOCKET                  g_CliSocketArr[MAXIMUM_WAIT_OBJECTS];
420 WSAEVENT                g_CliEventArr[MAXIMUM_WAIT_OBJECTS];
421 LPPER_IO_OPERATION_DATA g_pPerIODataArr[MAXIMUM_WAIT_OBJECTS];
422 DWORD WINAPI WorkerThread(LPVOID);
423 void Cleanup(int);
424 int main()
425 {
426   WSADATA     wsaData;
427   SOCKET      sListen, sClient;
428   SOCKADDR_IN local, client;
429   DWORD       dwThreadId;
430   int         iaddrSize = sizeof(SOCKADDR_IN);
431   // Initialize Windows Socket library
432   WSAStartup(0x0202, &wsaData);
433   // Create listening socket
434   sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
435   // Bind
436   local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
437 local.sin_family = AF_INET;
438 local.sin_port = htons(PORT);
439   bind(sListen, (struct sockaddr *)&local, sizeof(SOCKADDR_IN));
440   // Listen
441   listen(sListen, 3);
442   // Create worker thread
443   CreateThread(NULL, 0, WorkerThread, NULL, 0, &dwThreadId);
444   while (TRUE)
445   {
446     // Accept a connection
447     sClient = accept(sListen, (struct sockaddr *)&client, &iaddrSize);
448     printf("Accepted client:%s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
449     g_CliSocketArr[g_iTotalConn] = sClient;
450     
451     // Allocate a PER_IO_OPERATION_DATA structure
452     g_pPerIODataArr[g_iTotalConn] = (LPPER_IO_OPERATION_DATA)HeapAlloc(
453       GetProcessHeap(),
454       HEAP_ZERO_MEMORY,
455       sizeof(PER_IO_OPERATION_DATA));
456     g_pPerIODataArr[g_iTotalConn]->Buffer.len = MSGSIZE;
457     g_pPerIODataArr[g_iTotalConn]->Buffer.buf = g_pPerIODataArr[g_iTotalConn]->szMessage;
458     g_CliEventArr[g_iTotalConn] = g_pPerIODataArr[g_iTotalConn]->overlap.hEvent = WSACreateEvent();
459     // Launch an asynchronous operation
460     WSARecv(
461       g_CliSocketArr[g_iTotalConn],
462       &g_pPerIODataArr[g_iTotalConn]->Buffer,
463       1,
464       &g_pPerIODataArr[g_iTotalConn]->NumberOfBytesRecvd,
465       &g_pPerIODataArr[g_iTotalConn]->Flags,
466       &g_pPerIODataArr[g_iTotalConn]->overlap,
467       NULL);
468     
469     g_iTotalConn++;
470   }
471   
472   closesocket(sListen);
473   WSACleanup();
474   return 0;
475 }
476 DWORD WINAPI WorkerThread(LPVOID lpParam)
477 {
478   int   ret, index;
479   DWORD cbTransferred;
480   while (TRUE)
481   {
482     ret = WSAWaitForMultipleEvents(g_iTotalConn, g_CliEventArr, FALSE, 1000, FALSE);
483     if (ret == WSA_WAIT_FAILED || ret == WSA_WAIT_TIMEOUT)
484     {
485       continue;
486     }
487     index = ret - WSA_WAIT_EVENT_0;
488     WSAResetEvent(g_CliEventArr[index]);
489     WSAGetOverlappedResult(
490       g_CliSocketArr[index],
491       &g_pPerIODataArr[index]->overlap,
492       &cbTransferred,
493       TRUE,
494       &g_pPerIODataArr[g_iTotalConn]->Flags);
495     if (cbTransferred == 0)
496     {
497       // The connection was closed by client
498       Cleanup(index);
499     }
500     else
501     {
502       // g_pPerIODataArr[index]->szMessage contains the received data
503       g_pPerIODataArr[index]->szMessage[cbTransferred] = '\0';
504       send(g_CliSocketArr[index], g_pPerIODataArr[index]->szMessage,\
505         cbTransferred, 0);
506       // Launch another asynchronous operation
507       WSARecv(
508         g_CliSocketArr[index],
509         &g_pPerIODataArr[index]->Buffer,
510         1,
511         &g_pPerIODataArr[index]->NumberOfBytesRecvd,
512         &g_pPerIODataArr[index]->Flags,
513         &g_pPerIODataArr[index]->overlap,
514         NULL);
515     }
516   }
517   return 0;
518 }
519 void Cleanup(int index)
520 {
521   closesocket(g_CliSocketArr[index]);
522   WSACloseEvent(g_CliEventArr[index]);
523   HeapFree(GetProcessHeap(), 0, g_pPerIODataArr[index]);
524   if (index < g_iTotalConn - 1)
525   {
526     g_CliSocketArr[index] = g_CliSocketArr[g_iTotalConn - 1];
527     g_CliEventArr[index] = g_CliEventArr[g_iTotalConn - 1];
528     g_pPerIODataArr[index] = g_pPerIODataArr[g_iTotalConn - 1];
529   }
530   g_pPerIODataArr[--g_iTotalConn] = NULL;
531 }
532 
533 /*这个模型与上述其他模型不同的是它使用Winsock2提供的异步I/O函数WSARecv。在调用WSARecv时,指定一个WSAOVERLAPPED结构,这个调用不是阻塞的,也就是说,它会立刻返回。一旦有数据到达的时候,被指定的WSAOVERLAPPED结构中的hEvent被Signaled。由于下面这个语句
534 g_CliEventArr[g_iTotalConn] =g_pPerIODataArr[g_iTotalConn]->overlap.hEvent;
535 使得与该套接字相关联的WSAEVENT对象也被Signaled,所以WSAWaitForMultipleEvents的调用操作成功返回。
536 我们现在应该做的就是用与调用WSARecv相同的WSAOVERLAPPED结构为参数调用WSAGetOverlappedResult,从而得到
537 本次I/O传送的字节数等相关信息。在取得接收的数据后,把数据原封不动的发送到客户端,然后重新激活一个
538 WSARecv异步操作。
539 2.用完成例程方式实现的重叠I/O模型
540 */
541 #include <WINSOCK2.H>
542 #include <stdio.h>
543 #define PORT    5150
544 #define MSGSIZE 1024
545 #pragma comment(lib, "ws2_32.lib")
546 typedef struct
547 {
548 WSAOVERLAPPED overlap;
549 WSABUF        Buffer;
550   char          szMessage[MSGSIZE];
551 DWORD         NumberOfBytesRecvd;
552 DWORD         Flags; 
553 SOCKET        sClient;
554 }PER_IO_OPERATION_DATA, *LPPER_IO_OPERATION_DATA;
555 DWORD WINAPI WorkerThread(LPVOID);
556 void CALLBACK CompletionROUTINE(DWORD, DWORD, LPWSAOVERLAPPED, DWORD);
557 SOCKET g_sNewClientConnection;
558 BOOL   g_bNewConnectionArrived = FALSE;
559 int main()
560 {
561   WSADATA     wsaData;
562   SOCKET      sListen;
563   SOCKADDR_IN local, client;
564   DWORD       dwThreadId;
565   int         iaddrSize = sizeof(SOCKADDR_IN);
566   // Initialize Windows Socket library
567   WSAStartup(0x0202, &wsaData);
568   // Create listening socket
569   sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
570   // Bind
571   local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
572 local.sin_family = AF_INET;
573 local.sin_port = htons(PORT);
574   bind(sListen, (struct sockaddr *)&local, sizeof(SOCKADDR_IN));
575   // Listen
576   listen(sListen, 3);
577   // Create worker thread
578   CreateThread(NULL, 0, WorkerThread, NULL, 0, &dwThreadId);
579   while (TRUE)
580   {
581     // Accept a connection
582     g_sNewClientConnection = accept(sListen, (struct sockaddr *)&client, &iaddrSize);
583     g_bNewConnectionArrived = TRUE;
584     printf("Accepted client:%s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
585   }
586 }
587 DWORD WINAPI WorkerThread(LPVOID lpParam)
588 {
589 LPPER_IO_OPERATION_DATA lpPerIOData = NULL;
590   while (TRUE)
591   {
592     if (g_bNewConnectionArrived)
593     {
594       // Launch an asynchronous operation for new arrived connection
595       lpPerIOData = (LPPER_IO_OPERATION_DATA)HeapAlloc(
596         GetProcessHeap(),
597         HEAP_ZERO_MEMORY,
598         sizeof(PER_IO_OPERATION_DATA));
599       lpPerIOData->Buffer.len = MSGSIZE;
600       lpPerIOData->Buffer.buf = lpPerIOData->szMessage;
601       lpPerIOData->sClient = g_sNewClientConnection;
602       
603       WSARecv(lpPerIOData->sClient,
604         &lpPerIOData->Buffer,
605         1,
606         &lpPerIOData->NumberOfBytesRecvd,
607         &lpPerIOData->Flags,
608         &lpPerIOData->overlap,
609         CompletionROUTINE);      
610       
611       g_bNewConnectionArrived = FALSE;
612     }
613     SleepEx(1000, TRUE);
614   }
615   return 0;
616 }
617 void CALLBACK CompletionROUTINE(DWORD dwError,
618                                 DWORD cbTransferred,
619                                 LPWSAOVERLAPPED lpOverlapped,
620                                 DWORD dwFlags)
621 {
622   LPPER_IO_OPERATION_DATA lpPerIOData = (LPPER_IO_OPERATION_DATA)lpOverlapped;
623   
624   if (dwError != 0 || cbTransferred == 0)
625 {
626     // Connection was closed by client
627   closesocket(lpPerIOData->sClient);
628   HeapFree(GetProcessHeap(), 0, lpPerIOData);
629 }
630   else
631   {
632     lpPerIOData->szMessage[cbTransferred] = '\0';
633     send(lpPerIOData->sClient, lpPerIOData->szMessage, cbTransferred, 0);
634     
635     // Launch another asynchronous operation
636     memset(&lpPerIOData->overlap, 0, sizeof(WSAOVERLAPPED));
637     lpPerIOData->Buffer.len = MSGSIZE;
638     lpPerIOData->Buffer.buf = lpPerIOData->szMessage;    
639     WSARecv(lpPerIOData->sClient,
640       &lpPerIOData->Buffer,
641       1,
642       &lpPerIOData->NumberOfBytesRecvd,
643       &lpPerIOData->Flags,
644       &lpPerIOData->overlap,
645       CompletionROUTINE);
646    }
647 }
View Code