Winsock development network communication program classic entry

zhaozj2021-02-17  50

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 a server-side application 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: // Defines the network event socket serverSock; file: // Server side Socket Increase the following definition: Class CsocketSeverdlg: cdialog {... Public: Socket ClientSock [CLNT_MAX_NUM]; file: // Stores an array of Sockets with the client communication / * Processing function for various network asynchronous events * / void onclose (socket cursock); file: // Auto-Auto-End Socket Disconnect VOID Onsend (socket cursock); file: // Sends network packets VOID OnReceive (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) Defines the initialization network function, this function can be adjusted in the onInitDialog () of the socketseverdlg.cpp file. Bool csocketseverdlg :: initnetwork () {wsadata wsadata;

File: // Initialize the 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 (); wscheranup (); Return false;}

File: // Bind to the local port SockAddr_in localaddr; localaddr.sin_family = af_INET; LOCALADDR.SIN_PORT = HTONS (8888); file: // port number Do not conflict with other application conflicts Localadddddddddddddddddddddddddddddddddddddr.sin_addr.s_addr = 0; IF (Bind (ServerSock, (Struct Sockaddr *) & localaddr, sizeof (SOCKADDR)) = = Socket_ERROR) {MessageBox ("Binding Address Failed!"); CloseSocket; Wsacleanup (); Return False;} file: // Set SeverSock to asynchronous non-blocking mode and register various network asynchronous events, where m_hwnd file: // is the handle of the application's primary dialog or the 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 Listening Mode Return True;} Define the callback function of the network asynchronous event void csocketseverdlg :: OnNetEvent (WPARAM WPARAM, LPARAM LPARAM) { File: // Call the Winsock API function, get the network event type int tent = wsagetSelectEvent (LPARAM); file: // Call the Winsock API function to get the client cover of this event Socket Cursock = (Socket) WPARAM;

Switch (ievent) {copy 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 arrives at the event onreceive (CURSOCK); Break; Case FD_WRITE: FILE: // Sends Network Data Event Onsend (CURSOCK); Break; Default: Break;}} The following is a variety of network asynchronous events that occur on the corresponding socket The processing function, where the parameters sent in OnCept are the sockets created by the server side, onclose (), onRecEive (), and onsend () passed the parameters that the server is newly created when the server is accepted. The socket of the client communication. Void csocketseverdlg :: onaccept (socket cursock) {file: // Accept the connection request, and save the client to the client to communicate socket file: // Register for the new Socket, pay attention to the Accept event} void CsocketSeverdlg: : OnClose (SoCet Cursock) {file: // End communication with the corresponding client

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

New Post(0)