C++之SocketIO五种模型
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")
8int main()
9 {
10  WSADATA    wsaData;
11  SOCKET      sClient;
12  SOCKADDR_IN server;
13char        szMessage[MSGSIZE];
14int        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));
26while (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();
40return0;
41 }
42/*客户端所做的事情相当简单,创建套接字,连接服务器,然后不停的发送和接收数据。⽐较容易想到的⼀种服务器模型就是采⽤⼀个主线程,负责监听客户端的连接请求,当接收到某个客户端的连接请求后,创建⼀个专门⽤于和该客户端通信的 43⼀.选择模型
44Select(选择)模型是Winsock中最常见的I/O模型。之所以称其为“Select模型”,是由于它的“中⼼思想”便是利⽤select函数,实现对I/O的管理。最初设计该模型时,主要⾯向的是某些使⽤UNIX操作系统的计算机,它们采⽤的是Berkeley套接字⽅ 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")
52int    g_iTotalConn = 0;
53 SOCKET g_CliSocketArr[FD_SETSIZE];
54 DWORD WINAPI WorkerThread(LPVOID lpParameter);
55int main()
56 {
57  WSADATA    wsaData;
58  SOCKET      sListen, sClient;
59  SOCKADDR_IN local, client;
60int        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);
75while (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
84return0;
85 }
86 DWORD WINAPI WorkerThread(LPVOID lpParam)
87 {
88int            i;
89  fd_set        fdread;
90int            ret;
91struct timeval tv = {1, 0};
92char          szMessage[MSGSIZE];
93
94while (TRUE)
95  {
96    FD_ZERO(&fdread);
97for (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);
103if (ret == 0)
104    {
105// Time expired
106continue;
107    }
108for (i = 0; i < g_iTotalConn; i++)
109    {
110if (FD_ISSET(g_CliSocketArr, &fdread))
111      {
112// A read event happened on g_CliSocketArr
113        ret = recv(g_CliSocketArr, szMessage, MSGSIZE, 0);
114if (ret == 0 || (ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET))
115        {
116// Client socket closed
118            closesocket(g_CliSocketArr);
119if (i < g_iTotalConn - 1)
120            {
121                g_CliSocketArr[i--] = g_CliSocketArr[--g_iTotalConn];
122            }
123        }
124else
125        {
126// We received a message from client
127            szMessage[ret] = '\0';
128            send(g_CliSocketArr, szMessage, strlen(szMessage), 0);
129        }
130      }
131    }
132  }
133return0;
134 }
135/*服务器的⼏个主要动作如下:
1361.创建监听套接字,绑定,监听;
1372.创建⼯作者线程;
1383.创建⼀个套接字数组,⽤来存放当前所有活动的客户端套接字,每accept⼀个连接就更新⼀次数组;
1394.接受客户端的连接。这⾥有⼀点需要注意的,就是我没有重新定义FD_SETSIZE宏,所以服务器最多⽀持的并发连接数为64。⽽且,这⾥决不能⽆条件的accept,服务器应该根据当前的连接数来决定是否接受来⾃某个客户端的连接。⼀种⽐较好140实现的Condition Function。如下所⽰:
141*/
142int CALLBACK ConditionFunc(LPWSABUF lpCallerId,LPWSABUF lpCallerData,
143            LPQOS lpSQOS,LPQOS lpGQOS,LPWSABUF lpCalleeId, LPWSABUF lpCalleeData,GROUP FAR * g,DWORD dwCallbackData)
144 {
145if (当前连接数 < FD_SETSIZE)
146return CF_ACCEPT;
147else
148return CF_REJECT;
149 }
150/*⼯作者线程⾥⾯是⼀个死循环,⼀次循环完成的动作是:
1511.将当前所有的客户端套接字加⼊到读集fdread中;
1522.调⽤select函数;
1533.查看某个套接字是否仍然处于读集中,如果是,则接收数据。如果接收的数据长度为0,或者发⽣WSAECONNRESET错误,则表⽰客户端套接字主动关闭,这时需要将服务器中对应的套接字所绑定的资源释放掉,然后调整我们的套接字数组(154⼆.异步选择
155Winsock提供了⼀个有⽤的异步I/O模型。利⽤这个模型,应⽤程序可在⼀个套接字上,接收以Windows消息为基础的⽹络事件通知。具体的做法是在建好⼀个套接字后,调⽤WSAAsyncSelect函数。该模型最早出现于Winsock的1.1版本中,⽤于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);
165int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
166 {
167static 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 ;
181if (!RegisterClass(&wndclass))
182  {
183    MessageBox (NULL, TEXT ("This program requires Windows NT!"), szAppName, MB_ICONERROR) ;
184return0 ;
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);
199while (GetMessage(&msg, NULL, 0, 0))
200  {
201    TranslateMessage(&msg) ;
202    DispatchMessage(&msg) ;
203  }
204
205return msg.wParam;
206 }
207 LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
208 {
209  WSADATA      wsd;
210static SOCKET sListen;
211  SOCKET        sClient;
212  SOCKADDR_IN  local, client;
213int          ret, iAddrSize = sizeof(client);
214char          szMessage[MSGSIZE];
215switch (message)
216  {
217case 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);
234return0;
235case WM_DESTROY:
236    closesocket(sListen);
237    WSACleanup();
238    PostQuitMessage(0);
239return0;
recv函数242if (WSAGETSELECTERROR(lParam))
243    {
244      closesocket(wParam);
245break;
246    }
247
248switch (WSAGETSELECTEVENT(lParam))
249    {
250case 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);
256break;
257case FD_READ:
258      ret = recv(wParam, szMessage, MSGSIZE, 0);
259if (ret == 0 || ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET)
260      {
261        closesocket(wParam);
262      }
263else
264      {
265        szMessage[ret] = '\0';
266        send(wParam, szMessage, strlen(szMessage), 0);
267      }
268break;
269
270case FD_CLOSE:
271      closesocket(wParam);
272break;
273    }
274return0;
275  }
276
277return DefWindowProc(hwnd, message, wParam, lParam);
278 }
279
280/*在我看来,WSAAsyncSelect是最简单的⼀种Winsock I/O模型(之所以说它简单是因为⼀个主线程就搞定了)。使⽤Raw Windows API写过窗⼝类应⽤程序的⼈应该都能看得懂。这⾥,我们需要做的仅仅是:
2811.在WM_CREATE消息处理函数中,初始化Windows Socket library,创建监听套接字,绑定,监听,并且调⽤WSAAsyncSelect函数表⽰我们关⼼在监听套接字上发⽣的FD_ACCEPT事件;
2822.⾃定义⼀个消息WM_SOCKET,⼀旦在我们所关⼼的套接字(监听套接字和客户端套接字)上发⽣了某个事件,系统就会调⽤WndProc并且message参数被设置为WM_SOCKET;
2833.在WM_SOCKET的消息处理函数中,分别对FD_ACCEPT、FD_READ和FD_CLOSE事件进⾏处理;
2844.在窗⼝销毁消息(WM_DESTROY)的处理函数中,我们关闭监听套接字,清除Windows Socket library下⾯这张⽤于WSAAsyncSelect函数的⽹络事件类型表可以让你对各个⽹络事件有更清楚的认识:
285表1
286FD_READ 应⽤程序想要接收有关是否可读的通知,以便读⼊数据
287FD_WRITE 应⽤程序想要接收有关是否可写的通知,以便写⼊数据
288FD_OOB 应⽤程序想接收是否有带外(OOB)数据抵达的通知
289FD_ACCEPT 应⽤程序想接收与进⼊连接有关的通知
290FD_CONNECT 应⽤程序想接收与⼀次连接或者多点join操作完成的通知
291FD_CLOSE 应⽤程序想接收与套接字关闭有关的通知
292FD_QOS 应⽤程序想接收套接字“服务质量”(QoS)发⽣更改的通知
293FD_GROUP_QOS  应⽤程序想接收套接字组“服务质量”发⽣更改的通知(现在没什么⽤处,为未来
套接字组的使⽤保留)
294FD_ROUTING_INTERFACE_CHANGE 应⽤程序想接收在指定的⽅向上,与路由接⼝发⽣变化的通知
295FD_ADDRESS_LIST_CHANGE  应⽤程序想接收针对套接字的协议家族,本地地址列表发⽣变化的通知
296三.事件选择
297Winsock提供了另⼀个有⽤的异步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")
305int      g_iTotalConn = 0;
306 SOCKET  g_CliSocketArr[MAXIMUM_WAIT_OBJECTS];
307 WSAEVENT g_CliEventArr[MAXIMUM_WAIT_OBJECTS];
308 DWORD WINAPI WorkerThread(LPVOID);
309void Cleanup(int index);
310int main()
311 {
312  WSADATA    wsaData;
313  SOCKET      sListen, sClient;
314  SOCKADDR_IN local, client;
315  DWORD      dwThreadId;
316int        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);
330while (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 {
346int              ret, index;
347  WSANETWORKEVENTS NetworkEvents;
348char            szMessage[MSGSIZE];
349while (TRUE)
350  {
351    ret = WSAWaitForMultipleEvents(g_iTotalConn, g_CliEventArr, FALSE, 1000, FALSE);
352if (ret == WSA_WAIT_FAILED || ret == WSA_WAIT_TIMEOUT)
353    {
354continue;
355    }
356    index = ret - WSA_WAIT_EVENT_0;
357    WSAEnumNetworkEvents(g_CliSocketArr[index], g_CliEventArr[index], &NetworkEvents);
358if (NetworkEvents.lNetworkEvents & FD_READ)
359    {
360// Receive message from client
361      ret = recv(g_CliSocketArr[index], szMessage, MSGSIZE, 0);
362if (ret == 0 || (ret == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET))
365      }
366else
367      {
368        szMessage[ret] = '\0';
369        send(g_CliSocketArr[index], szMessage, strlen(szMessage), 0);
370      }
371    }
372if (NetworkEvents.lNetworkEvents & FD_CLOSE)
373  {
374    Cleanup(index);
375  }
376  }
377return0;
378 }
379void Cleanup(int index)
380 {
381  closesocket(g_CliSocketArr[index]);
382 WSACloseEvent(g_CliEventArr[index]);
383if (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对象数组,394同样的,这⾥的程序没有考虑两个问题,⼀是不能⽆条件的调⽤accept,因为我们⽀持的并发连接数有限。
395解决⽅法是将套接字按MAXIMUM_WAIT_OBJECTS分组,每MAXIMUM_WAIT_OBJECTS个套接字⼀组,每⼀组分配⼀个
396⼯作者线程;或者采⽤WSAAccept代替accept,并回调⾃⼰定义的Condition Function。第⼆个问题是没有对连接数
397为0的情形做特殊处理,程序在连接数为0的时候CPU占⽤率为100%。
398四.重叠I/O模型
399Winsock2的发布使得Socket I/O有了和⽂件I/O统⼀的接⼝。我们可以通过使⽤Win32⽂件操纵函数ReadFile和
400WriteFile来进⾏Socket I/O。伴随⽽来的,⽤于普通⽂件I/O的重叠I/O模型和完成端⼝模型对Socket I/O也适⽤了。
401这些模型的优点是可以达到更佳的系统性能,但是实现较为复杂,⾥⾯涉及较多的C语⾔技巧。例如我们在完成端⼝
402模型中会经常⽤到所谓的“尾随数据”。
4031.⽤事件通知⽅式实现的重叠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;
414char          szMessage[MSGSIZE];
415  DWORD        NumberOfBytesRecvd;
416  DWORD        Flags;
417 }PER_IO_OPERATION_DATA, *LPPER_IO_OPERATION_DATA;
418int                    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);
423void Cleanup(int);
424int main()
425 {
426  WSADATA    wsaData;
427  SOCKET      sListen, sClient;
428  SOCKADDR_IN local, client;
429  DWORD      dwThreadId;
430int        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);
444while (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,
455sizeof(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,
4631,
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();
474return0;
475 }
476 DWORD WINAPI WorkerThread(LPVOID lpParam)
477 {
478int  ret, index;
479  DWORD cbTransferred;
480while (TRUE)
481  {
482    ret = WSAWaitForMultipleEvents(g_iTotalConn, g_CliEventArr, FALSE, 1000, FALSE);
483if (ret == WSA_WAIT_FAILED || ret == WSA_WAIT_TIMEOUT)
484    {
485continue;
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);
495if (cbTransferred == 0)
496    {
497// The connection was closed by client
498      Cleanup(index);
499    }
500else
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,
5101,
511        &g_pPerIODataArr[index]->NumberOfBytesRecvd,
512        &g_pPerIODataArr[index]->Flags,
513        &g_pPerIODataArr[index]->overlap,
514        NULL);
515    }
516  }
517return0;
518 }
519void Cleanup(int index)
520 {
521  closesocket(g_CliSocketArr[index]);
522  WSACloseEvent(g_CliEventArr[index]);
523  HeapFree(GetProcessHeap(), 0, g_pPerIODataArr[index]);
524if (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。在调⽤WSARe
cv时,指定⼀个WSAOVERLAPPED结构,这个调⽤不是阻塞的,也就是说,它会⽴刻返回。⼀旦有数据到达的时候,被指定的WSAOVERLAP 534g_CliEventArr[g_iTotalConn] =g_pPerIODataArr[g_iTotalConn]->overlap.hEvent;
535使得与该套接字相关联的WSAEVENT对象也被Signaled,所以WSAWaitForMultipleEvents的调⽤操作成功返回。
536我们现在应该做的就是⽤与调⽤WSARecv相同的WSAOVERLAPPED结构为参数调⽤WSAGetOverlappedResult,从⽽得到
537本次I/O传送的字节数等相关信息。在取得接收的数据后,把数据原封不动的发送到客户端,然后重新激活⼀个
538WSARecv异步操作。
5392.⽤完成例程⽅式实现的重叠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;
550char          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);
556void CALLBACK CompletionROUTINE(DWORD, DWORD, LPWSAOVERLAPPED, DWORD);
557 SOCKET g_sNewClientConnection;
558 BOOL  g_bNewConnectionArrived = FALSE;
559int main()
560 {
561  WSADATA    wsaData;
562  SOCKET      sListen;
563  SOCKADDR_IN local, client;
564  DWORD      dwThreadId;
565int        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);
579while (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;
590while (TRUE)
591  {
592if (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,
598sizeof(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,
6051,
606        &lpPerIOData->NumberOfBytesRecvd,
607        &lpPerIOData->Flags,
608        &lpPerIOData->overlap,

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。