Introduction to the development of network communication programs using asynchronous non-blocking Socket Winsock

Source: Internet
Author: User
Tags network function

A classic entry to WinSock to develop network communication programs


For many beginners, a common phenomenon in the development of network communication programs is that it is difficult to start. Many concepts such as sync, async, block, and unblock are confusing for beginners, I only know it, so I don't know why.


The synchronous mode refers to the communication mode in which the sender sends the next packet without receiving the response from the receiver. asynchronous means that after the sender sends the data, the sender receives the response from the receiver, to send the next packet.

A blocked socket is a network call that is performed on this socket until the call is successful. Otherwise, it is blocked on this network call. For example, you can call the Recv () function to read data in the network buffer, if no data arrives, it will always be mounted on the Recv () function call until some data is read, and this function call will not be returned; A non-blocking socket is a network call for this socket. It is returned immediately regardless of whether the call is successful or not. For example, if you call the Recv () function to read data in the network buffer, the system immediately returns the data no matter whether the data is read or not, instead of sticking to the function call. In actual windows network communication software development, asynchronous non-blocking sockets are the most commonly used. Normally, software in the C/S (Client/Server) structure is in asynchronous non-blocking mode.

For these concepts, the understanding of beginners may be only plausible. I will use a simple example to illustrate the basic principle and working mechanism of asynchronous non-blocking socket. The objective is to give beginners a thorough understanding of the concept of socket asynchronous non-blocking, and also provide them with a quick start method for developing network communication applications using socket. The operating system is Windows 98 (or NT4.0), and the development tool is Visual C ++ 6.0.

MFC provides an asynchronous class casyncsocket, which encapsulates the basic functions of asynchronous and non-blocking sockets and is convenient to use as a commonly used network communication software. However, it shields the asynchronous and non-blocking Socket concepts. Developers do not need to understand the principles and working mechanisms of asynchronous and non-blocking sockets. Therefore, it is recommended that beginners do not use the classes provided by MFC when learning to compile network communication programs. Instead, they should use Winsock2 API first to help them understand asynchronous and non-blocking socket programming mechanisms.

For the sake of simplicity, the applications on the server and client are based on the MFC standard dialog box, and the network communication part is implemented based on the Winsock2 API.
First, make the server application.
Use the MFC Wizard to create a dialog box-based application socketsever. Do not select the windwos sockets option in step 3. After completing the project, create a seversock, set it to asynchronous non-blocking mode, register various Asynchronous Network events for it, and then contact the custom Asynchronous Network events, finally, set it to the listening mode. In the callback function of custom Network Asynchronous events, you can obtain various Network Asynchronous events and perform different processing based on their types. The following describes how to write the relevant code.
Before defining the socketseverdlg. h file class, add the following definition:

# Define network_event wm_user + 166 file: // defines network events

Socket serversock; file: // server socket
Add the following definition to the class definition:
Class csocketseverdlg: cdialog
{
Public:
Socket clientsock [clnt_max_num]; file: // array of the socket that stores the communication with the client

/* Functions for handling various Asynchronous Network events */
Void onclose (socket cursock); file: // The remote socket is disconnected.
Void onsend (socket cursock); file: // sends network packets
Void onreceive (socket cursock); file: // network packet arrival
Void onaccept (socket cursock); file: // Client Connection Request

Bool initnetwork (); file: // initialize the Network Function
Void onnetevent (wparam, lparam); file: // asynchronous Event Callback Function
...
};

Add message ing in the socketseverdlg. cpp file, where onnetevent is the asynchronous Event Callback Function Name:
On_message (network_event, onnetevent)
Define the network initialization function. You can call this function in oninitdialog () of the socketseverdlg. cpp file.
Bool csocketseverdlg: initnetwork ()
{
Wsadata;

// Initialize the TCP protocol
Bool ret = wsastartup (makeword (2, 2), & wsadata );
If (Ret! = 0)
{
MessageBox ("network protocol initialization failed! ");
Return false;
}

// Create a server socket
Serversock = socket (af_inet, sock_stream, ipproto_tcp );
If (serversock = invalid_socket)
{
MessageBox ("failed to create socket! ");
Closesocket (serversock );
Wsacleanup ();
Return false;
}

// Bind to a local port
Sockaddr_in localaddr;
Localaddr. sin_family = af_inet;
Localaddr. sin_port = htons (8888); // do not conflict with other applications
Localaddr. sin_addr.s_addr = 0;
If (BIND (serversock, (struct sockaddr *) & localaddr, sizeof (sockaddr ))
= Socket_error)
{
MessageBox ("binding address failed! ");
Closesocket (serversock );
Wsacleanup ();
Return false;
}
 
// Set seversock to asynchronous non-blocking mode and register various Asynchronous Network events for it, where m_hwnd
// Handle the Main Dialog Box or main window of the application
If (wsaasyncselect (serversock, m_hwnd, network_event, fd_accept | fd_close | fd_read | fd_write) = socket_error)
{
MessageBox ("failed to register Asynchronous Network events! ");
Wsacleanup ();
Return false;
}
Listen (serversock, 5); file: // sets the listening mode
Return true;
}

The following describes the Network Asynchronous Event Callback Function.
Void csocketseverdlg: onnetevent (wparam, lparam)
{
// Call the Winsock API function to obtain the network event type.
Int ievent = wsagetselectevent (lparam );

// Call the Winsock API function to obtain the client socket for this event
Socket cursock = (socket) wparam;

Switch (ievent)
{
Case fd_accept: // Client Connection Request event
Onaccept (cursock );
Break;
Case fd_close: // client disconnection event:
Onclose (cursock );
Break;
Case fd_read: // network packet arrival event
Onreceive (cursock );
Break;
Case fd_write: // send Network Data Events
Onsend (cursock );
Break;
Default: break;
}
}

The following are the processing functions for various Asynchronous Network events that occur on the corresponding socket. The onaccept parameter is the socket created on the server, onclose (), onreceive (), and onsend () the passed parameters are all newly created socket for communication with the client when the server accepts the client connection.
Void csocketseverdlg: onaccept (socket cursock)
{
// Accept the connection request and save the socket for communication with the client initiating the connection request
// Register an asynchronous event for the new socket. Note that no accept event exists.
}
 
Void csocketseverdlg: onclose (socet cursock)
{
// End the communication with the corresponding client and release the corresponding resources
}

Void csocketseverdlg: onsend (socet cursock)
{
// Perform preprocessing when sending data to the client
}

Void csocketseverdlg: onreceive (socet cursock)
{
// Read the data packets in the network buffer.
}

Create a client application in the same way. Initialize the network. You do not need to set the socket to the listening mode. When an asynchronous event is registered, no fd_accept exists, but the fd_connect event is added. Therefore, the onaccept () function is not available, but the onconnect () function is added. When sending a connection request to the server, use the connect () function. After the connection is successful, it will respond to the onconnect () function. The following is the definition of the onconnect () function. The passed parameters indicate whether the connection sent from the client socket and the server is successful.
Void csocketclntdlg: onconnect (socket cursock, int error)
{
If (0 = Error)
{
If (cursock = clntsock)
MessageBox ("connection to the server successful! ");
}
}
Define the onreceive () function to process network data arrival events;
Define the onsend () function to process network data sending events;
Define the onclose () function to handle server close events.

The above is the basic method of using the asynchronous I/O model based on the Windows message mechanism for server and client applications. You can also use the event model, overlap model, or port model. For more information, see related books.
After implementing the above example, you will have a certain understanding of the mechanism of the Winsock network communication program. Next, you can perform more exciting programming, not only to transmit common data on the Internet, but also to transmit voice and video data, you can also make a server software for network resource sharing by yourself, you can share your achievements with your colleagues in the LAN of the lab.
 

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.