Overlapped I/O 完成例程要求用户提供一个回调函数,发生新的网络事件的时候系统将执行这个函数。 系统用WorkerRoutine函数处理接收到的数据。
1 #include <WINSOCK2.H>
2 #include <stdio.h>
3
4 #define PORT 5150
5 #define MSGSIZE 1024
6
7 #pragma comment(lib, "ws2_32.lib")
8
9 typedef struct
10 {
11 WSAOVERLAPPED overlap;
12 WSABUF Buffer;
13 char szMessage[MSGSIZE];
14 DWORD NumberOfBytesRecvd;
15 DWORD Flags;
16 SOCKET sClient;
17 }PER_IO_OPERATION_DATA, *LPPER_IO_OPERATION_DATA;
18
19 DWORD WINAPI WorkerThread(LPVOID);
20
21 void CALLBACK CompletionROUTINE(DWORD, DWORD, LPWSAOVERLAPPED, DWORD);
22
23 SOCKET g_sNewClientConnection;
24
25 BOOL g_bNewConnectionArrived = FALSE;
26
27 int main()
28 {
29 WSADATA wsaData;
30 SOCKET sListen;
31 SOCKADDR_IN local, client;
32 DWORD dwThreadId;
33 int iaddrSize = sizeof(SOCKADDR_IN);
34 // Initialize Windows Socket library
35 WSAStartup(0x0202, &wsaData);
36 // Create listening socket
37 sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
38 // Bind
39 local.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
40 local.sin_family = AF_INET;
41 local.sin_port = htons(PORT);
42 bind(sListen, (struct sockaddr *)&local, sizeof(SOCKADDR_IN));
43 // Listen
44 listen(sListen, 3);
45 // Create worker thread
46 CreateThread(NULL, 0, WorkerThread, NULL, 0, &dwThreadId);
47 while (TRUE)
48 {
49 // Accept a connection
50 g_sNewClientConnection = accept(sListen, (struct sockaddr *)&client, &iaddrSize);
51 g_bNewConnectionArrived = TRUE;
52 printf("Accepted client:%s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
53 }
54 }
55 DWORD WINAPI WorkerThread(LPVOID lpParam)
56 {
57 LPPER_IO_OPERATION_DATA lpPerIOData = NULL;
58 while (TRUE)
59 {
60 if (g_bNewConnectionArrived)
61 {
62 // Launch an asynchronous operation for new arrived connection
63 lpPerIOData = (LPPER_IO_OPERATION_DATA)HeapAlloc(
64 GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(PER_IO_OPERATION_DATA));
65
66 lpPerIOData->Buffer.len = MSGSIZE;
67 lpPerIOData->Buffer.buf = lpPerIOData->szMessage;
68 lpPerIOData->sClient = g_sNewClientConnection;
69
70 WSARecv(lpPerIOData->sClient,
71 &lpPerIOData->Buffer,
72 1,
73 &lpPerIOData->NumberOfBytesRecvd,
74 &lpPerIOData->Flags,
75 &lpPerIOData->overlap,
76 CompletionROUTINE);
77
78 g_bNewConnectionArrived = FALSE;//这很重要
79 }
Sleep()是不可唤醒的,也就是说一直睡到时间结束。 SleepEx()是可以唤醒的,可以被消息唤醒 The SleepEx function causes the current thread to enter a wait state until one of the following occurs: 1)An I/O completion callback function is called 2)An asynchronous procedure call (APC) is queued to the thread. 3)The time-out interval elapses
80 SleepEx(1000, TRUE);
81 }
82 return 0;
83 }
84 void CALLBACK CompletionROUTINE(DWORD dwError,
85 DWORD cbTransferred,
86 LPWSAOVERLAPPED lpOverlapped,
87 DWORD dwFlags)
88 {
89 LPPER_IO_OPERATION_DATA lpPerIOData = (LPPER_IO_OPERATION_DATA)lpOverlapped;
90
91 if (dwError != 0 || cbTransferred == 0)
92 {
93 // Connection was closed by client
94 closesocket(lpPerIOData->sClient);
95 HeapFree(GetProcessHeap(), 0, lpPerIOData);
96 }
97 else
98 {
99 lpPerIOData->szMessage[cbTransferred] = '\0';
100 send(lpPerIOData->sClient, lpPerIOData->szMessage, cbTransferred, 0);
101
102 // Launch another asynchronous operation
103 memset(&lpPerIOData->overlap, 0, sizeof(WSAOVERLAPPED));
104 lpPerIOData->Buffer.len = MSGSIZE;
105 lpPerIOData->Buffer.buf = lpPerIOData->szMessage;
106 WSARecv(lpPerIOData->sClient,
107 &lpPerIOData->Buffer,
108 1,
109 &lpPerIOData->NumberOfBytesRecvd,
110 &lpPerIOData->Flags,
111 &lpPerIOData->overlap,
112 CompletionROUTINE);
113 }
114 }
用完成例程来实现重叠I/O比用事件通知简单得多。在这个模型中,主线程只用不停的接受连接即可;辅助线程判断有没有新的客户端连接被建立,如果有,就为那个客户端套接字激活一个异步的WSARecv操作,然后调用SleepEx使线程处于一种可警告的等待状态,(按我的理解就是辅助线程主动的放弃一段时间的CPU使用权,以防止一直处于阻塞状态)以使得I/O完成后CompletionROUTINE可以被内核调用。如果辅助线程不调用SleepEx,则内核在完成一次I/O操作后,无法调用完成例程(因为完成例程的运行应该和当初激活WSARecv异步操作的代码在同一个线程之内)。当重叠IO操作完成,SleepEx会被完成的消息唤醒,从而使得辅助线程中的完成例程得到执行。
完成例程内的实现代码比较简单,它取出接收到的数据,然后将数据原封不动的发送给客户端,最后重新激活另一个WSARecv异步操作。注
意,在这里用到了“尾随数据”。我们在调用WSARecv的时候,参数lpOverlapped实际上指向一个比它大得多的结构PER_IO_OPERATION_DATA,这个结构除了WSAOVERLAPPED以外,还被我们附加了缓冲区的结构信息,另外还包括客户端套接字等重要的信息。这样,在完成例程中通过参数lpOverlapped拿到的不仅仅是WSAOVERLAPPED结构,还有后边尾随的包含客户端套接字和接收数据缓冲区等重要信息。这样的C语言技巧在我后面介绍完成端口的时候还会使用到。
的
来源:https://www.cnblogs.com/NeuqUstcIim/archive/2008/08/17/1269678.html