Winsock network communication program design

xiaoxiao2021-03-06  73

For many beginners, the development of network communication procedures, a common phenomenon is that it feels difficult to start. Many concepts such as: Synchronization (SYNC) / asynchronous (Async), Block / Non-Block, etc.

The synchronization method refers to the sender's unequal receiver response, and then sends a communication method of the next packet; and after the transmission party issues the data, the response is received by the receiver, only one packet is issued. way of communication.

Blocking socket refers to the network call of this socket until it is returned until success, otherwise it is blocked on this network call, such as calling the RECV () function to read the data in the network buffer, if there is no data arrival, This function call is returned until you read some data until you read some data, and the non-blocking socket refers to the network call to which this socket is executed, it will return immediately whether it is successful. . For example, call the RECV () function to read the data in the network buffer, and return it immediately whether it is read or not, it will not be hanging on this function call. In actual Windows network communication software development, asynchronous non-blocking sockets are used. The software of the usual C / S (client / server) structure is asynchronous non-blocking mode.

For these concepts, the understanding of beginners may only be similar to, I will use a simplest example to explain the basic principles and working mechanisms of asynchronous non-blocking sockets. The purpose is to let beginners have a very thorough understanding of the concept of Socket asynchronous non-blocking, but also give them a quick entry method for developing network communication applications with Socket. The operating system is Windows 98 (or NT4.0), and the development tool is Visual C 6.0.

The MFC provides an asynchronous class CasyncSocket that encapsulates the basic functions of asynchronous, non-blocking sockets, which is very convenient to do commonly used network communication software. However, it shields the concept of Socket asynchronous, non-blocking, etc., developers do not need to understand the principles and working mechanisms of asynchronous, non-blocking sockets. Therefore, it is recommended that beginners learn to edit the network communication program, do not use the class of the MFC to use the class, and first use the Winsock2 API, which helps to understand the asynchronous, non-blocking SOCKET programming mechanism.

For the sake of simplicity, both the server-side and client applications are based on the MFC-based standard dialog, and the network communication part is implemented based on the WINSOCK2 API.

Do server-side applications first

Use the MFC Wizard to make a dialog-based application SocketSever, note that you do not select the WindWos Sockets option in the third step. After doing a good job, create a severSock, set it as an asynchronous non-blocking mode, and register a variety of network asynchronous events, then contact it with the custom network asynchronous event, and finally set it to the listening mode. In the callback function of the custom network asynchronous event, you can get a variety of network asynchronous events, depending on their type, do different processing. The following will be described in detail how to write related code.

Add the following definition before the class definition of the socketseverdlg.h file:

#define network_event wm_user 166 file: // Define Network Events Socket ServerSock; File: // Server Socket

Increase in class definitions as follows:

Class CsocketSeverdlg: cdialog {... public: socket clientsock [CLNT_MAX_NUM]; file: // Stores an array of Sockets with the client communication / * Processing function of various network asynchronous events * / void onclose (socket cursock); file: // Convection Socket Disconnect VOID ONSEND (Socket Cursock); file: // Sends Network Packet Void OnRecEVE (socket Cursock); file: // Network Packet Reaches Void OnAccept (socket cursock); file: // Client connection request BOOL INITNETWORK (); file: // Initialization Network Functions Void OnNetEvent (WPARAM WPARAM, LPARAM LPARAM); File: // Asynchronous Event Tune Function ...}; Add message mapping in socketseverdlg.cpp file, where OnNetEvent is an asynchronous event callback function name:

ON_MESSAGE (NetWork_Event, OnNetEvent)

Define the initialization network function, and adjust this function in the OnInitDialog () of the socketseverdlg.cpp file.

Bool csocketseverdlg :: initten wsadata; file: // Initializes TCP protocol BOOL RET = WSAStartup (MakeWord (2, 2), & WSADATA); if (Ret! = 0) {MessageBox ("Initialization Network Agreement failed!" Return False;} file: // Create server-side socket serverSock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ServerSock == Invalid_Socket) {MessageBox ("Create a socket failed!"); CloseSocket (ServerSocket ); Wsacleanup (); return false;} file: // Bind to local port on a port SockAddr_in localaddr; localaddr.sin_family = AF_INET; LOCALADDR.SIN_PORT = HTONS (8888); File: // Port number Do not do with other applications conflict localaddr.sin_addr.s_addr = 0; if (bind (ServerSock, (struct sockaddr *) & localaddr, sizeof (sockaddr)) = = SOCKET_ERROR) {MessageBox ( "bind address failed!"); closesocket (ServerSock); WSACleanup ( ); return: // Set severSock Set to asynchronous non-blocking mode, and register various network asynchronous events, where m_hwnd file: // is the handle IF for the application's primary dialog or main window (WSaasyncselect " (Serversock, M_HWND, Network_EVENT, FD_ACCEPT | FD_CLOSE | FD_READ | FD_WRITE) == Socket_ERROR) {MessageBox ("Register Network Asynchronous Event Failed!"); Wsacleanup (); Return False;} Listen (Serversock, 5); file: / / Set the listening mode Return True;}

The callback function of the network asynchronous event is defined below

Void csocketseverdlg :: OnNETEVENT (WPARAM WPARAM, LPARAM LPARAM) {file: // Call the Winsock API function, get the network event type int = wsagetSelectEvent (LPARAM); file: // Call the Winsock API function to get the client that occurs Socket Socket Cursock = (Socket) WPARAM; Switch (IEvent) {Case FD_ACCEPT: File: // Client Connection Request Event Onaccept (CURSOCK); BREAK; Case FD_Close: File: // Client Intercom: OnClose CURSOCK; BREAK; CASE FD_READ: FILE: // Network Packet Arrival Event OnRecEive (CURSOCK); Break; Case FD_WRITE: File: // Send Network Data Event Onsend (CURSOCK); BREAK; Default: Break;}} The following is The processing function of various network asynchronous events that occur on the corresponding socket, where the parameters passed by onconPt are the socket created by the server side, onclose (), onreceive (), and onsend () pass the parameters all the server is the server side. The newly created Socket created with this client is accepted.

Void csocketseverdlg :: onaccept (socket cursock) {file: // Accept the connection request, and save the client to the client to communicate SocketFile: // Register for the new Socket, pay attention to no accept event} Void CsocketSeverdlg :: OnClose (SoCet Cursock) {file: // End communication with the corresponding client, release the corresponding resource} Void CsocketSeverdlg :: Onsend (SOCET CURSOCK) {file: // Do related prerequisites when sending data to the client} Void CsocketSeverdlg :: OnReceive (SOCET CURSOCK) {file: // Reads the packets in the network buffer}

Establish a client application with the same method. Initialize the network part, it is not necessary to set the socket to the listening mode. When registering an asynchronous event, there is no fd_accept, but add the fd_connect event, so there is no onaccept () function, but adds the onConnect () function. When sending a connection request to the server, use the connect () function, after the connection is successful, it will respond to the onConnect () function. Below is the definition of the onConnect () function, the transferred parameters are signs that the client socket and the server are connected to whether the connection is successful.

Void CsocketClntdlg :: onConnect (Socket Cursock, Int Error) {if (0 = = error) {if (cursock = = clntsock) MessageBox ("Connection Server Success!");}}

Define the onRecEive () function, process network data arrival event;

Define an onsend () function to process the sending network data event;

Define the onClose () function, process the shutdown event of the server.

The above is the basic method of servers and client applications with an asynchronous I / O model based on a Windows message mechanism. You can also use event models, overlapping models, or complete port models, readers can refer to the relevant books.

After implementing the above example, you will have a certain understanding of the mechanism of Winsock's network communication program. Next you can make more exciting programming, not only can transfer normal data on the Internet, but also to transmit voice, video data, you can also make a network resource shared server software, and your classmates in the Laboratory Laboratory You can share your results together.

转载请注明原文地址:https://www.9cbs.com/read-92520.html

New Post(0)