阅读背景:

三.Windows I/O模型之事件选择(WSAEventSelect )模型

来源:互联网 
 1 SOCKET Socket[WSA_MAXIMUM_WAIT_EVENTS];//64
2 WSAEVENT event[WSA_MAXIMUM_WAIT_EVENTS];
3 SOCKET accept,listen;
4 DWORD eventTotal=0;
5 DWORD index;
6
7 //创建套接字
8 listen=socket(...);
9
10 //绑定本地地址
11 bind(...);
12
13 //创建事件对象
14 WSAEVENT newEvent;
15 newEvent=WSACreateEvent();
16
17 //注册网络事件
18 WSAEventSelect(listen,newEvent,FD_ACCEPT|FD_CLOSE);
19
20 Socket[eventTotal]=listen;
21 event[eventTotal]=newEventl;
22 eventTotal++;
23
24
25 while(1)
26 {
27 //等待事件触发状态
28 index=WSAWaitForMultipleEvents(eventTotal,event,FALSE,WSA_INFINITE,FALSE);
29
30 //查看发生的网络事件类型,确定发生网络事件的套接字
31 WSANETWORKEVENTS networkEvents;
32 WSAEnumNetworkEvents(Socket[index-WSA_WAIT_EVENT_0],event[index-WSA_WAIT_EVENT_0],&networkEvents);
33
34 //确定发生的网络事件类型
35 if(networkEvents.lNetworkEvents&FD_ACCEPT)
36 {
37 if(networkEvents.iErrorCode[FD_ACCEPT_BIT]!=0)
38 {
39 printf("FD_ACCEPT failed with error %d\n",networkEvents.iErrorCode[FD_ACCEPT_BIT]);
40 break;
41 }
42
43 //FD_ACCEPT事件发生后,则进行后续处理
44 accept=accept(Socket[index_WSA_WAIT_EVENT_0],NULL,NULL);
45
46 //查看事件对象的数目
47 if(eventTotal>WSA_MAXIMUM_WAIT_EVENTS)
48 {
49 printf("too many connections\n");
50 closesocket(accept);
51 break;
52 }
53
54 //再次创建事件,再次进行上述操作,进行循环
55 newEvent=WSACreateEvent();
56
57 WSAEventSelect(listen, newEvent, FD_READ|FD_WRITE | FD_CLOSE);
58
59 event[eventTotal]=newEvent;
60 Socket[eventTotal]=accept;
61 eventTotal++;
62 printf("socket %d connected\n",accept);
63 }
64
65 //FD_READ事件的处理
66 //雷同于FD_ACCEPT网络事件的处理
67 if(networkEvents.lNetworkEvents&FD_READ)
68 {
69 if(networkEvents.iErrorCode[FD_READ_BIT]!=0)
70 {
71 printf("FD_READ failed with error %d\n",networkEvents.iErrorCode[FD_READ_BIT]);
72 break;
73 }
74 //读取数据
75 recv(Socket[index-WSA_WAIT_EVENT_0],buf,sizeof(buf),0);
76 }
77
78 //接下来其他网络事件的处理同上,但是需要注意一点,事件选择模型是基于窗口程序的,并且需要消息发送,只是这部分代码为给出而已
79
80 }
81
82
83
84
View Code

分享到: