Use of non-blocking sockets for C + + (2)

Source: Internet
Author: User

Continue the topic-Asynchronous non-blocking communication in software.

Because the software is based on MFC, the CAsyncSocket class is used to implement asynchronous communication.

The first step is to understand the CAsyncSocket asynchronous mechanism, referencing the

http://blog.csdn.net/tianhai110/article/details/2115270.

Since CAsyncSocket uses asynchronous non-blocking mechanisms, you can always contract and receive packages at any time.

Send and receive functions are asynchronous non-blocking, can be completed in an instant, so the transceiver interleaved. Because of this, only the calling

They do not guarantee the completion of sending or receiving. For example, sending a function send, calling it may have 3 results: error, partial completion,

All done. There are two kinds of errors: one is a failure caused by various network problems, you need to decide immediately to abandon this operation,

The other is "busy" and you don't actually have to ignore it right away. You need to call GetLastError to determine what kind of situation

GetLastError returns WSAEWOULDBLOCK, stands for "Busy", why when you send to get wsaewouldblock but

No need to ignore it? Because CAsyncSocket will remember your sendwsaewouldblock, the data to be sent will be written

CAsyncSocket the internal send buffer, and will automatically call OnSend when not busy, send data in the internal buffer.

Similarly, if send is only partially completed, you do not need to ignore it, and the data that has not been sent is also written to the CAsyncSocket internal

Send buffer, and automatically call OnSend when not "busy" to complete the send.

As with OnSend assist send to complete the work, Onrecieve, OnConnect, OnAccept will also assist recieve,

Connect, accept to complete the work. All of this is done through the messaging mechanism.

Before you can use CAsyncSocket, you must call AfxSocketInit to initialize the Winsock environment, and AfxSocketInit

Creates a hidden Csocketwnd object that can receive Windows messages because this object is derived from CWnd. On the one hand it

Will accept the status report of each CAsyncSocket, on the other hand it can capture various socket events issued by the system. So it can become

A bridge between the high-level CAsyncSocket object and the Winsock bottom: for example, a CAsyncSocket wsaewouldblock at send,

It will send a message to Csocketwnd as a report, Csocketwnd will maintain a report registration form when it receives the underlying Winsock

When an idle message is made, the report registration form is retrieved, and the reporter's OnSend function is called directly. So the casyncsocket of the above-mentioned

will automatically call OnXxx, which is actually wrong, the real caller is csocketwnd--it is a CWnd object that runs in a separate thread.

The above is the principle of casyncsocket, and the specific code is as follows (receiving side):

First declare the class that inherits from CAsyncSocket in the header file, and override the three methods:

#include <afxsock.h>classCmyasyncsocket: Publiccasyncsocket{ Public: Cmyasyncsocket (void); ~cmyasyncsocket (void); Virtual voidOnClose (intNerrorcode); Virtual voidOnConnect (intNerrorcode); Virtual voidOnReceive (intnerrorcode);};

Implement these three methods in the CPP file separately:

voidCmyasyncsocket::onclose (intNerrorcode) {    if(0==Nerrorcode)    {Close (); } casyncsocket::onclose (Nerrorcode);}voidCmyasyncsocket::onconnect (intNerrorcode) {    if(0==Nerrorcode) {        //TODO: Create an action after a connection} casyncsocket::onconnect (Nerrorcode);}voidCmyasyncsocket::onreceive (intNerrorcode) {    if(0==Nerrorcode) {        //TODO: Post-acceptance processing
        Char szrcv[513] = "";
        int nrcved = Receive (szrcv,15);     }    casyncsocket::onreceive (Nerrorcode);}

Next, you can call this class in a file that needs to be communicated:

    cmyasyncsocket m_pclientsocket;     AfxSocketInit ();               M_pclientsocket.create ();    M_pclientsocket.connect (_t ("IP"), PORT);

There are three places to be aware of during use:

1. AfxSocketInit () initialization prior to use;

2. If a message can only be accepted once, notice that the onreceive () of the parent class is called after receive ();

3. In one method, no other code can appear after the Connect () function (this is unclear).

Use of non-blocking sockets for C + + (2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.