Winsock API programming introduction

zhaozj2021-02-08  262

Winsock API programming introduction

Author: table email: tablejiang@21cn.com

I believe that many people are interested in network programming. Let's introduce the most widely used programming interface Winsock API in network programming.

Using Winsock API programming, you should learn about the basics of TCP / IP. Although you can use the Winsock API to write web applications, but you must write outstanding web applications, or you must have some understanding of TCP / IP protocol of.

1. The relationship between TCP / IP protocols and Winsock network programming interfaces.

Before you start, let's talk about what Winsock and TCP / IP do.

I met a lot of people asked me: How to use Winsock protocol program? In fact, this is a bit wrong. Winsock is not a network protocol. He is just a network programming interface, that is, he is not an agreement, but he can visit a lot. A web protocol, you can treat him as some protocols. The current Winsock has basically realized the agreement. You can use Winsock to call the functions of multiple protocols.

So, what is the relationship between Winsock and TCP / IP protocol? In fact, Winsock is a package of TCP / IP protocol, you can call TCP / IP's various functions by calling the Winsock interface function. For example, I want to use TCP / IP protocol sends data, you can use Winsock's interface function send () to call TCP / IP's sending data function, as for how to send data, Winsock has helped you package this feature.

2.TCP / IP protocol introduction

Now introduce some of the principles of TCP / IP. TCP / IP protocol contains very wide range, he is a four-layer agreement, including various, hardware software requirements, us only introduce software knowledge .TCP The ip protocol is the exact statement that the TCP / UDP / IP protocol should be.

UDP protocol (User DataGram Protocol User Data). It is a transmission of message boundaries that do not guarantee reliable data. TCP protocol (Transmission Control Protocol Transmission Control Protocol). It is a streaming protocol. He provides reliable , Orderly, two-way,-facing-oriented transmission.

3. Protect message boundaries and streams

So what is the protection of the message boundary and stream?

Protect the message boundary, means that the transfer protocol uses the data as a separate message to transmit the independent message. This means that there is a protection message boundary, and the receiving end can only receive one packet issued by the sender. The flow-oriented is to refer to the boundary without the protection message protection. If the transmitting end continuously transmits the data, the receiving end may receive two or more packets in one reception operation.

We will give such examples, for example, we send three packets, the size is 2K, 4K, 8K, these three packets, have reached the network stack of the receiving end, if you use the UDP protocol, no matter where we use How big to receive the buffer to receive data, we must have three reception actions to receive all the packets. And use the TCP protocol, we can set the received buffer size in 14k, we can once The packet is received. It only needs to have a reception action.

This is because the Protection Message Border of the UDP protocol makes each message are independent. The stream is transmitted as a string of data, and he doesn't think the data is a message.

Therefore, many people do not know when using TCP protocols, the TCP is based on stream transmission. When they continue to send data, they often know TCP will lose. In fact, because the buffers they use are large enough When they may receive two or more packets at a time, and many people tend to ignore this, only analyze the first packet, and other packets that have been received are ignored. So If you want to make this type of network programming, you must pay attention to this.

4. Winsock programming simple process

Let's introduce the WINSOCK programming method of the Win32 platform. The communication must have the server side, and the client. We briefly introduce the general flow of the TCP server.

For any Winsock-based programming first we must initialize the Winsock DLL library. Int WSASTARUP (Word WversionRequested, LvrsionRequested is the version of Winsock we request us, calling this interface function can help us initialize Winsock. Then we have to create one Socket (socket). Socket socket (int Af, int type, int protocol); socket can be said to be the core of Winsock Communication. All data transfer of Winsock Communication is completed by sockets, set The word contains two information, one is an IP address, one is the port number, uses these two information, we can determine any of the communication nodes in the network. When we call the socket () interface function created a set After the word, we must connect the socket to the address you need to communicate, we can implement this connection through the binding function. Int Bind (socket S, const strulect sockaddr far * name, int namelen); struct sockaddr_in {Short Sin_Family; u_short sin_prot; struct in_addr sin_addr; char sin_sero [8];} Contains the local address we need to establish a connection, including, address family, IP, and port information. SIN_FAMILY field We must set him to AF_INET, This is telling Winsock to use IP address family .sin_prot is the port number we want to communicate .sin_addr is the IP address information we want to communicate.

Here, you must have to mention the Little-endian ''. Because the method of various computer processing data is different, the Intel 86 processor is used. The small head 'situation is to represent the number of multi-bytes, that is, put the low byte in front, put the high byte behind, but the Internet standard is just the opposite, so we must convert the host byte into network bytes. Order. Thewinsock API provides several functions.

Transform host bytes into network bytes; u_long htonl (u_long hostlong); u_short htons (u_short hostshort); transform network bytes into host bytes; u_long ntohl; u_short nto Hs (u_short netshort This, this, when we set the IP address, and the PORT port, we must use the bind () function to bind the socket and addresses after the host byte is converted into network bytes.

When the bind is completed, the server side must establish a listener queue to receive the client's connection request. Int listen (socket s, int backlog); this function can transfer the socket to the listening mode. If the client has Connection request, we must also use int Accept (Socket S, Struct Sockaddr Far * Addr, Int Far * Addrlen); to accept the client's request. Now we have basically completed the establishment of a server, and the process of establishing the client It is initialized Winsock and then creates a socket socket, and then use Int Connect (Socket S, Const Struct SockAddr Far * Name, Int Namelen) to connect the server.

Below is an example of the simplest creation server side: server-side creation: WSADATA WSD; Socket Slisd; Socket Sclient; uint port = 800; int ostdrsize; struct sockaddr_in local, client; wsastartup (0x11, & wsd); slisten = socket (AF_INET, SOCK_STREAM, IPPOTO_IP); local.sin_family = AF_INET; local.sin_addr = htonl (INADDR_ANY); local.sin_port = htons (port); bind (sListen, (struct sockaddr *) & local, sizeof (local)); Listen (Slisten, 5); SCLIENT = Accept (Slisten, (Struct SockAddr *) & Client, & Iaddrsize); Create of the client: WSADATA WSD; Socket Sclient; uint port = 800; char Szip [] = "127.0.0.1"; int iAddrSize; struct sockaddr_in server; WSAStartup (0x11, & wsd); sClient = socket (AF_INET, SOCK_STREAM, IPPOTO_IP); server.sin_family = AF_INET; server.sin_addr = inet_addr (szIp); server.sin_port = htons (port); connect ( SCLIENT, STRUCKADDR *) & Server, SIZEOF (Server));

Once the server is connected to the client, Int Send (Socket S, Const Char Far * Buf, Int Len, Int Flar Far * BUF, whether it is the client or the server, or the server side; int RECV (Socket S, Char Far * BUF , int LEN, INT FLAGS; function to receive and send data, because the TCP connection is two-way. When you want to turn off the communication link, you can call int shutdown (socket s, int how); turn off the set The specified function of the word. Turn the INT CloseSocket (Socket S); turn off the socket handle. Such a communication process is completed.

Note: The above code does not check the function return value. If you do network programming, you must check the result of the calling result of any Winsock API function, because many times the function call is not necessarily successful. The function described above, the return value type is Int If the function call fails, the return is socket_ERROR.

5. Winsock programming five models

The method described above is just the simplest Winsock communication, and many network communication has many unexpected accidents.

For example, Winsock provides two socket modes: locking and non-locking. When we use lock sockets, we use a lot of functions, such as Accpet, Send, Recv, etc. If there is no data need to be processed, these functions Not returning, that is, your app will block the call of the function. If you use non-blocking mode, call these functions, no matter if you have data arrive, he will return, so it is possible that we are In the non-blocking mode, there is a failure to call these functions, so we need us to handle many accidents.

This is obviously not what we want to see. We can use Winsock's communication model to avoid these conditions.

Winsock provides five socket I / O models to solve these problems. They are SELECT, WSAASYNCSELECT (Asynchronous Selection), WSAEventSelect (Event Selection), Overlapped, Completion Port, We Here you will introduce the two models of SELECT, WSAASYNCSELECT.

The SELECT model is the most common I / O model. Use int SELECT (int NFDS, FD_SET FAR * READFDS, FD_SET FAR * WRITEFDS, FD_SET FAR * EXCEPTFDS, CONST STRUCT TIMEVAL FAR * TIMEOUT); function to check the Socket set you want to call Whether the terminal already has a data that needs to be processed. SELECT contains three Socket queues, represents: readfds, check readability, WriteFDs, checks, exceptfds, exception data. Timeout is the return time of the SELECT function. For example, We want to check if a socket has data needs to be received, we can add a socket handle to the readability check queue, then call Select, if the socket does not receive the data, the SELECT function will put the set The log is removed from the readability check queue, so we can know if the socket handle is still exhibited in the readability queue, you can know that there is no data to be received.

Winsock provides some macros to operate the socket queue fd_set. Fd_clr (s, * set) from the queue set delete the handle S. FD_ISSET (S, * SET) Check if the handle S is existing with the queue set. Fd_set (S, * Set) Add the handle S into the queue set. FD_ZERO (* SET) initializes the set queue into an air queue.

WSaasyncselect (Asynchronous Selection) Model: The WSAAsyncSelect model is to connect a window and socket handle. When the network event of the socket occurs, it will send a message to the window, then you can respond to the message response function on the window. Receive and send the data in the middle. INT WSAASYNCSELECT (Socket S, HWND HWND, UNSIGNED INT WMSG, Long LEVENT); This function can be connected to the socket handle and window, WMSG is a message we must customize. Levent It is a developed network event. Includes fd_read, fd_write, fd_accept, fd_connect, fd_close. Several events. For example, I need to receive FD_READ, FD_WRITE, FD_CLOSE network event. You can call WSAAsYNCselect (s, hwnd, wm_socket, fd_read | fd_write | fd_close This way, when there is fd_read, fd_write, or fd_close network event, window hWnd will receive a WM_Socket message, what is the event of the LPARAM logo of the message parameter.

In fact, everyone should have seen this model because MFC's CSocket class is to use this model.

The above introduces some methods of Winsock programming.

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

New Post(0)