Windows Network Programming classic entry

Source: Internet
Author: User

 

For a beginner in Windows network programming, the following method is a classic entry.
Beginners are advised not to use the classes provided by MFC, but to use Windows APIs as a simple server and client, which helps them understand the socket programming mechanism.
For the sake of simplicity, the application is a standard Dialog Box Based on MFC.
Winsock is implemented using Windows API:
(1) The server has two threads:
Main thread-you need to write the following functions to implement

# Define network_event user_message + 100 file: // defines network events
Sockaddr_in clientaddr; file: // temporarily store the Client IP Address

File: // customize the message ing function to map the network events defined above to the processing function
File: // onnetevent is a network event handler, which is defined below
On_message (network_event, onnetevent );

In the initialization function in your dialog box, call the following sub-function for network initialization.
Bool initnetwork () file: // initialize the network
{
File: // initialize the TCP protocol
Bool ret = wsastartup (makeword (2, 2), & wsadata );
If (Ret! = 0)
{
MessageBox ("failed to initialize socket! ");
Return false;
}

File: // create a server socket
Socket serversocket
= Socket (af_inet, sock_stream, ipproto_tcp );
If (serversocket = invalid_socket)
{
MessageBox ("failed to create socket! ");
Closesocket (m_socket );
Wsacleanup ();
Return false;
}

File: // bind to a local port
Sockaddr_in localaddr;
Localaddr. sin_family = af_inet;
Localaddr. sin_port = htons (1688 );
Localaddr. sin_addr.s_addr = 0;
If (BIND (serversocket, (const struct sockaddr *) & localaddr,
Sizeof (sockaddr) = socket_error)
{
MessageBox ("binding address failed! ");
Closesocket (m_socket );
Wsacleanup ();
Return false;
}

File: // registers Asynchronous Network events. m_hwnd is the main dialog box of the application or the handle of the main window.
Wsaasyncselect (serversocket, m_hwnd, network_event,
Fd_accept | fd_close | fd_read | fd_write );

Listen (serversocket, 5); file: // sets the listening mode
 
Return true;
}

File: // defines the network event Response Function
Void onnetevent (wparam, lparam)
{
File: // call the API function to obtain the network event type.
Int ievent = wsagetselectevent (lparam );

File: // get the client socket that sends this event
Socket psock = (socket) wparam;

Switch (ievent)
{
Case fd_accept: file: // Client Connection Request
{
Onaccept ();

Break;
}
Case fd_close: file: // client disconnection event:
{
Onclose (psock );
Break;
}
Case fd_read: file: // network packet arrival event
{
Onreceive (psock );
Break;
}
Case fd_write: file: // send Network Data Events
{
Onsend (psock );
Break;
}
Default: break;
}
}

Void onaccept (socet psock) file: // response to the Client Connection Request function
{
Int Len = sizeof (sockaddr );

File: // call the API function, accept the connection, and return a new socket.
File: // You can also obtain the Client IP address.
Socket clientsocket = accept (serversocket,
(Struct sockaddr *) & clientaddr, & Len );

File: // register an asynchronous event for the new socket. Note that no accept event exists.
If (wsaasyncselect (clientsocket, m_hwnd, ip_event,
Fd_close | fd_read | fd_write) = socket_error)
{
MessageBox ("An error occurred while registering the asynchronous event! ");
Return;
}
 
File: // a self-compiled function that saves the client-related information: socket,
// Ip address and logon time
Saveclientsocket (clientsocket, clientaddr, currenttimer );
}

Void onclose (socet psock)
{
File: // compile the function to end the communication with the corresponding client, release the corresponding resources, and perform corresponding processing.
Endclientsocket (psock );
}

Void onsend (socet psock)
{
File: // a self-compiled function that performs preprocessing when sending data to the client.
Handleonsend (psock );
}

Void onreceive (socet psock)
{
Recv (...); file: // call the API function to read data packets in the network buffer.

File: // a self-compiled function that combines the data packet with the client that sends the data.
File: // clientsocket encapsulates a network message
Buildnetmsg (...);

File: // a self-compiled function that puts the network message into a message queue and is processed by the worker thread.
Savenetmsg (...);
Setevent (...); file: // trigger the working thread with the event object
}

After logging on to the client, the client sends its computer name to the server. After receiving the computer name, the server saves it. In this way, the server can display information about all online clients, including the client computer name, IP address, and logon time.

Note: the client does not have the onaccept () function, but has the onconnect () function.

Worker thread-
Create and start a working thread during app Initialization

Afxbeginthread (workthread, this, thread_priority_normal );
File: // This may be the main dialog box of the application or the handle of the main window.

Uint workthread (lpvoid pparam)
{
While (1)
{
File: // wait for multiple events to arrive
Int ret = waitformultipleobject (...);

Switch (RET)
{
Case object_0:
{
If (bnewnetmsg) file: // check whether a new network message exists in the Network Message Queue
{
Readnetmsg (...); file: // read if a new network message exists.
Handlenetmsg (...); file: // process this network message
}
Break;
}
Case object_0 + 1:
{
File: // exit
Break;
}
Default: break;
}

Return 0;
}

The client is a single thread. When logging on to the server, use the connect () function to send a connection request to the server;
The client does not have the onaccept () function, but has the onconnect () function.
Preprocessing when sending connection requests in the onconnect () function;
Respond to and process network data in the onreceive () function;
Respond to server close events in the onclose () function;
Preprocessing of data sending in the onsend () function;

If you want to implement online communication between clients (called chat rooms), you can also use UDP protocol on the client.
Create a multicast model for the LAN with multiple-Point-to-multi-point, and talk to you later. Implement the above program first.

The above I/O asynchronous model is based on the Windows message mechanism. In addition, you can use the event model, overlap model, or the port model,
We recommend that you refer to books such as Windows Network Programming Guide.

If you are familiar with the above mechanism, you must have understood the mechanism of the Winsock network program. Next, you can perform more exciting programming, not only to transmit common data on the Internet, and also
To transmit voice and video data, you can create a chat room and 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.