Teach you to play the Socket model overlap I / O
"As a beginner, you can often feel the hardships of beginners. So I always want to take the time to do what I can help those who need help. I also hope that everyone can learn and others. Share together, don't despise others to get greed, because you should not be despised, you should not pay. "
----- Inventive By PiggyXP (Pig)
Forehead
In fact, I should first apologize, because I am in July, I want to write a set of entrance articles about Socket model and the matching code, but I didn't expect to go out to vacation by the beauty of the beauty, just returned. . . . . . -_- b In fact, I have been basically written, but I don't write a set of text, but I think it is a little difficult model, because other models are entitled to be simple.
However, since it is also an initiator, he is still looking forward to it.
This article condenses the author's heart, if you want to reprint, please indicate the original author and the source, thank you! ^ _ ^
OK, Let's Go! Have Fun! ! q ^ _ ^ P
Sample source code download address for this article
(The multi-client MFC code written by VC.NET 2003 is equipped with detailed comments, just a simple display of the characters from the client, and a little improvement is a chat room):
http://piggyxp.download.9cbs.net/
(Updated Download Address in 2009, currently available)
(This article is assumed to have the ability to program the simple model of Socket, if you don't know if you don't know about this series, please pay attention to this series of other articles)
table of Contents:
1. Advantages of overlapping models
2. Basic principle of overlapping model
3. Basic knowledge about overlapping models
4. Implementation steps for overlapping models
5. Multiple client conditions
One. Advantages of overlapping models
1. You can run all Windows platforms that support Winsock2, and unlike completed ports just support NT systems.
2. Compare the I / O (Overlapped I / O) model to make the application to better system performance than a model such as blocking, select, wsaasyncselect, and WSAEventSelect, and WSAEventSelect, which enables applications to achieve better system performance.
Because it and the four models are different, the application that uses overlapping models notifies the buffer transceiver system directly using data, that is, if the application delivers a 10kb size buffer to receive data, and data has arrived The data will be directly copied to the delivery buffer.
And these four models, data arrive and copy into a single-socket receiving buffer, at which time the application will be informed of the capacity to be read. When the application calls the reception function, the data is copied from a single-set buffer buffer to the application's buffer, and the difference is reflected.
3. It can be seen from the test results provided in Windows Network Programming, in which the P4 1.7G Xero processor (CPU is very strong) and the 768MB response server can process more than 40,000 Socket connections. When the CPU usage is around 40%, the CPU usage is only about 40% - very good performance, it has been completed to complete the port ^ _ ^
two. Basic principle of overlapping model
Said so many benefits, you must also jump, but we still have to mention the basic principles of overlapping models.
Summary, the overlapping model is to allow the application to use the overlapping data structure (WSAOVERLAPPED), deliver one or more WINSOCK I / O requests at a time. For these requests, after they are completed, the application will receive a notification, so you can process these data through your own code.
It should be noted that there are two methods to manage the completion of overlapping IO requests (that is, notification to the completion of overlapping operations): 1. Event object notification (Event Object Notification)
2. Completion routines, pay attention, not completing the port here
This article only tells how to use event notifications to achieve overlapping IO models, and the method of completion routines is ready to put it :) (Too much content, one writing is not finished), if there is no special instructions, The overlapping model of this paper defaults to an overlapping model based on an event notification.
Since it is based on event notifications, the Windows event object is required to associate with the WSAOverlapped structure (there is a corresponding parameter in the WSAOVERLAPPED structure), which is popular, that is. . . . Yes, forgot to say, since it is necessary to use overlapping structure, we often use Send, Sendto, RECV, and Recvfrom is also replaced by Wsasend, Wsasendto, WSARECV, Wsarecvfrom, and their usage I will talk, here only It is necessary to pay attention to a point, there is an overlapped parameter in their parameters. We can assume that the operation of our WSARECV is "bind" to this overlap structure, submit a request, other things will be handed over to overlapping structure And the overlapping structure is "binding" with Windows event object so that we can "enjoy it" after the WSARECV will "share it", wait until the overlapping operation is completed, naturally there will be corresponding events to notify us to do , Then we can take our desired data according to the result of overlapping operations.
Maybe I haven't understood it for a long time, then continue to look back. . . . . . . -_- b, language expressibility is limited ~~~
three. Basic knowledge about overlapping models
Here is to introduce and exemplify several critical functions that will be used in the program to write overlapping models.
WSAOVERLAPPED structure
This structure is naturally the core in the overlapping model, which is called so definition
Typedef struct _wsaoverlapped {
DWORD INTERNAL
DWORD INTERNALH;
DWORD OFFSET;
DWORD OFFSETHIGH;
WSAEVENT HEVENT; / / The only parameter that needs attention to associate WSAEVENT objects
} WSAOVERLAPPED, * LPWSAOVERLAPPED;
We need to deliver WSARECV and other operations to a overlapping structure, and we need an event object "binding" with overlapping structure to inform us to complete the completion of the operation, see and hevent parameters, don't tell you, you should know How to bring the event object to the overlapping structure? Roughly is as follows:
WSAEVENT EVENT; / / Define events
WSAOVERLAPPED ACCEPTOVERLAPPED; / / Define overlapping structure
Event = wsacreateEvent (); // Establish an event object handle
ZeromeMory (& AcceptoverLapped, SizeOf (Wsaoverlapped)); // Initializing overlapping structure
Acceptoverlapped.hevent = event; // done !!
2. WSARECV Series Function
In the overlapping model, the received data is to rely on it. Its parameters are more than the RECV, because it is necessary to overlap the structure, it is defined: int wsarecv (
Socket S, // is of course a socket that delivers this operation
LPWSABUF LPBUFFERS, / / Receive buffer, different from the RECV function
// This requires an array that is composed of a WSABUF structure.
DWord dwbuffercount, // The number of WSABUF structures in the array
LPDWORD LPNUMBEROFBYTESRECVD, // If the receiving operation is complete, you will return a function call here.
// Number of bytes received
LPDWORD LPFLAGS, // said that the length is long, we set it here to 0
LPWSAOVERLAPPED LPOVERLAPPED, / / "Bind" overlap structure
LPWSAOVERLAPPED_COMPLETION_ROUTINE LPCOMPLETIONROUTINE
// The parameters that will be used in the completion routine will be set here as NULL.
);
return value:
WSA_IO_PENDING: The most common return value, which means that our WSARECV operation is successful, but
I / O operation has not been completed, so we need to bind an event to notify us when to do
For example: (the order of the definition of the variable and the order of the above description are corresponding, the same)
Socket S;
WSABUF DATABUF; / / Define buffers for WSABUF structures
// Initialize DataBuf
#define data_bufsize 5096
Char buffer [data_bufsize];
ZeromeMory (buffer, Data_bufsize);
DataBuf.len = DATA_BUFSIZE;
DataBuf.buf = buffer;
DWORD dwbuffercount = 1, dwrecvbytes = 0, FLAGS = 0;
/ / Establish needed overlapping structure
WSAOVERLAPPED Acceptoverlapped; // If you want to handle multiple operations, here is of course a need
// WSAOVERLAPPED array
WSAEVENT Event; // If you want multiple events, here, there is of course a WSAEVENT array
// Need to note is that a socket will have more than one overlap request at the same time.
// will also correspond to more than one WSAEVENT
Event = wsacreateevent ();
ZeromeMory (& AcceptoverLapped, Sizeof (Wsaoverlapped);
Acceptoverlapped.hevent = event; // Key one step, "bind" to the overlapping structure
// Make so much work, I can finally use WSARECV to deliver our request to overlapping structure, call. . . .
WSARECV (S, & DataBuf, dwbuffercount, & dwrecvbytes,
& Flags, & acceptoverlapped, null;
Other functions, I will not introduce it here, because we have such a good helper after all, and I will talk about some ^ _ ^ when the completion routine and complete port are completed.
3. WSAWAITFORMULTIPEEVENTS function
Friends who are familiar with the WSAEventSelect model will definitely be unfamiliar with this function. In fact, everyone should not be unfamiliar, this function is still like a WaitFormultiPleObjects function commonly used in the thread, because all are waiting for an event. Trigger. Because we need events to notify us of the completion of the overlapping operation, it naturally requires the function of this waiting event with it.
DWORD WSAWAITFORMULTIPEEVENTS
DWORD CEVENTS, / / Waiting Events Total Quantity
CONST WSAEVENT * LPHEVENTS, / / Event array pointer
Bool fwaitall, // This should be said more questions:
// If set to True, all events are sent to the event when all events are communicated.
// False, any event is sent to the signal to return
// We must set it to false here.
DWORD DWTIMEOUT, // Timeout, if the timeout, the function returns WSA_WAIT_TIMEOUT
// If set to 0, the function will return immediately
// If set to WSA_INFINITE, only the event will be returned after being sent.
/ / Not recommended here for WSA_INFINITE because. . . Let's talk about it later ..-_- b
Bool falrtable // This parameter will be used in the completion routine, here we set it to false
);
return value:
WSA_WAIT_TIMEOUT: The most common return value, what we need to do is to continue WAIT
WSA_WAIT_FAILD: An error occurred, please check if both CEVENTS and LPHEVENTS are valid.
If an event in an event array is communicated, the function returns the index value of this event, but this index value requires minus predefined values WSA_WAIT_EVENT_0 is the location in the event array.
The specific example will not be held here, and will also say
Note: The WSAWAITFORMULTIPEEVENTS function can only support a maximum of the WSA_Maximum_Wait_Events object, is 64, that is, WSAWAITFORMULTIPEEvents can only wait for 64 events, if you want to wait more than 64 events, you will create additional worker threads, you must Don't manage a thread pool, this is not as follows by the following completion routine model.
4. WsagetoverlappedResult function
Since we can get a notification completed by the WSAWAITFormultipleEvents function, then we naturally need a function to query the result of overlapping operations, defined as follows
Bool WsagetoverlappedResult
Socket S, // Socket, no need to say
LPWSAOVERLAPPED LPOVERLAPPED, / / This is a pointer to the overlapping structure we want to query the result
LPDWORD LPCBTRANSFER, / / / / The number of bytes of actual reception (or send) this overlap operation
Bool fwait, // Set to true unless the overlapping operation is completed, otherwise the function will not return
/ / Set False, and the operation is still in the suspended state, then the function will return false
// Error is WSA_IO_Incomplete
// But because we are waiting for the event to notify us to do this, we set up
// It doesn't have any effects in it ... ..-_- b Don't still egg, I also want to say some ...
LPDWORD LPDWFLAGS / / Pointer to DWORD, responsible for receiving results logo);
This function is not difficult. We don't need to pay attention to its return value, you can fill in the parameters directly, here will not exist first.
The only thing to pay attention to is if the WSAGETOVERLAPPEDRESULT is complete, the third parameter returns to 0, then the communication other party has closed the connection. The Socket on our side has turned off.