Simple Winsock Application Design (1)

xiaoxiao2021-03-05  36

Simple Winsock Application Design (1) Lin Army believes that readers have basically aware of Winsock's definition, system environment, and some Winsock Stack and Winsock applications. Next, I hope that I can introduce a simple WINSOCK network application design for readers. Based on the 46 Application Interface (API) defined by Winsock 1.1 specification, we will step by step by step to establish a pair of TCP Socket mainfast from the schema (CLIENT / Server). In these two programs, Server will create Socket links, shutdown, and data delivery, etc., will use the "Asynchronous" function provided by Winsock; ). Since our focus is not in MS Windows SDK programming, we will use the easiest way to display messages; Tips for MS Windows programs, please study the relevant books and articles by readers. Today, let's first take a look at the main connection (CONNECT) and close (close) of the master from the architecture TCP Socket. (See Figure 1.) (Figure 1. TCP socket connection establishment and closing from the architecture), before, the author has simply introduces the concept of the master from the architecture, now we will explain more exclusive examples in life, readers a little It is also easy to understand the description of the author. We can assume that Server is like some of the services provided by the Telecommunications Bureau, such as "104 review" or "112 obstacles". (1) The Telecommunications Bureau first established a telephone switch, which is like a call socket () in the call. (2) The Telecommunications Bureau is then set to 104, just like we call the bind (), specify the Server's socket specified (bind) in a port. Of course, the Telecommunications Bureau must let the user know this number; and our client program also knows the port used by Server, and there is a way to connect. (3) There will be some auto-service extensions under the 104 review table of the telecommunications office, but its number is limited, so sometimes you will not pass this number (busy line). Similarly, when we create a TCP's server socket, we will call the listen () in a letter to listen; the second parameter of listen () is the number of waiting queue, and the usual value is from 1 to 5. (In fact, the two are still a bit different.) (4) The user knows this 104 check-number service of the Telecom Bureau, and he can use a phone to dial to connect this service. This is why we client open an identical TCP Socket, then call the connect () to connect the port specified by Server. Of course, like the phone, if Waiting Queue is full, your connection will fail when it is unable to serve, or if Server does not provide this service, your connection will fail. (5) After receiving the call of this inquiry, the Tripline of the Telecommunications Bureau has turned to another extension, and the switchboard itself returns to the waiting state.

Server Listening Socket is also the same, when you call the Accept () card, the Server's system creates a new Socket to serve this connection, and the original socket will return to the status of the listener. (6) When you have finished the query, you can hang on the phone, and you will be offline. This is also true of Socket closing between Client and Server; however, this shuts down the offline action, can be shut down by the Client or Server. Some phone query systems are not the same? Next, we will look at how the main TCP socket is reached with these Winsock functions; and uses a function in the Winsock Stack in the WINSOCK Stack in the WINSOCK STACK in the Sockets. Only those of the articles are listed in the article, and the complete program is visible to the appendix. [Server Establish Socket and enter the listening wait status] First, let's take a look at the Server end to create a TCP Socket and enable it to listen to the wait. In Figure 1. We can see the first call to the WSAStartup (). The following: WSAStartup (): Connect the application with the first function of Winsock.dll. Format: int PASCAL FAR WSAStartup (WORD wVersionRequested, LPWSADATA lpWSAData); Parameters: wVersionRequested want to use the Windows Sockets API version lpWSAData point WSADATA information index Return value: Success - 0 defeat - WSASYSNOTREADY / WSAVERNOTSUPPORTED / WSAEINVAL Description: This function " Must be the first in the application call to the Windows Sockets DLL function, and only this function is successful after the call is successful, and the other Windows Sockets DLL can be called. This file also allows users to specify the Windows Sockets API version to use, and get some information from the designer. In the program, we have to use Winsock 1.1, so we have a section in the program: WSASTARTUP ((1 << 8) | 1), ((Word) ((Word) ((1 << 8) | 1) means that we want to use the Winsock "1.1" version, and WSADATA is used to store some information about this WinSock Stack. Let's call the socket () in a "TCP Socket" Socket (): Established Socket. Format: Socket Pascal Far Socket (INT AF, INT TYPE, INT Protocol); Parameters: AF currently only provides PF_INET (AF_INET) TYPE SOCKET (SOCK_STREAM, SOCK_DGRAM) Protocol Communication Agreement (if The user is not specified, set to 0) Passage: Success - Socket's identification code failed - INVALID_SOCKET (Call wsagetlasterror () Reason: This one is used to create a socket, and establish its site for this SOCKET Use resources.

Socket type can be a Stream Socket or DataGram Socket? We have to build TCP socket, so our second parameter is SOCK_STREAM, we will record this Socket number in Listen_SD. Listen_SD = Socket (PF_INET, SOCK_STREAM, 0) Next We want to specify a location and port to the SOCKET for Server, which client know which port will be connected? So we call bind () . Bind (): Specifies the local location of the Socket (AddRess). Format: Int Pascal Far Bind (Socket S, Const Struct Sockaddr Far * Name, Int Namelen); Paramese: s Socket Deficker Name Socket Address Name Dax Address Delivery Value: Success - 0 Failed - Socket_ERROR (Call WsagetLastError () can be learned to know: This one is specified to specify the local location and port gives an unnamed Socket. If the user does not at the address or port value, then he can set the location to INADDR_Addr_any, and port is 0; then Windows Sockets will automatically set it appropriate and port (1024 to 5000) ), The user can call GetSockName () when the SOCKET is really connected, and the value is called to know the value set. BIND () VOC wants to specify the order and port, this address must be the IP address of the machine in this program, so if the reader can set the address to INADDR_any when designing the program, so that the Winsock system will automatically The correct location is filled in. If you want to make the program only on a machine, set the location to the IP address of the machine. Since this end is a Server end, we must specify a port number to this Socket. Readers must pay attention to it, once the TCP Socket has selected a location and port, it is no longer able to call another bind to change its location or port. In the program we specify the port of the Server end to 7016, the address is set by the system. struct sockaddr_in sa; sa.sin_family = PF_INET; sa.sin_port = htons (7016); / * port number * / sa.sin_addr.s_addr = INADDR_ANY; / * address * / bind (listen_sd, (struct sockaddr far *) & sa, SIZEOF (SA)) We will use htons () in this group when specifying the Port number, mainly because the numerical read mode of each machine is different (the PC and UNIX system are different), so we use this letter to Host Order arrangements are converted into a NetWork ORDER arrangement; the same ground, we can also call NTOHS () to restore it.

(Host Order machine is different, but NetWork Order is the same) (Htons is aimed for short values, and after the value of "with HOTNL and NTOHL), after we call Listen (), let this socket enter Monitor status. The TCP Socket of a Server side must accept the connection of the Client end after you have finished the list of Listen. Listen (): Sets Socket to the listening status, ready to be connected. Format: Int Pascal Far Listen (Socket S, INT Backlog); Parameters: S Socket Identification Code Backlog Unspeakable to Complete Complete Connection Requirements The maximum number of transmitted values ​​of the connection requirements of each other: Success - 0 failed - SOCKET_ERROR (Call WsageTlasterror () can be learned) Description: The user can use this file to set the socket to enter the listening state, and set up to how many of the ports that do not really complete the connection before the connection. (At present, the maximum value is limited to 5, the minimum is 1), we set backlog to 1. Listen (Listen_SD, 1) After the call is Listen, if the Client end is connected, the connection action of the Client side will succeed, but the Server end must call the Accept () in this time, it is formally completed the Server end. Connection action. But when can we know the client end to connect, while a timely call is ACCEPT? Here we have to use a good WSAAsyncSelect letter, turn the SOCKET of the Server to the Asynchronous mode, let the system actively to inform us that there is Client to connect. (Figure 1. This card is not drawn) WSAAsYNCselect (): Requires a Socket event (event) notify the user when an event occurs. Format: Int Pascal Far WSaasyncselect (socket s, hwnd hwnd, unsigned int wmsg, long levent); Parameters: s socket number HWND Action is completed, the message-receiving window Handle WMSG Remove the message of the window of the Window LEVENT application is interested in the network Road Event Passage Value: Success - 0 Failed - Socket_ERROR (Call Wsagetlasterror () Reasons Reasons) Description: This function is to request the user to request Windows Sockets DLL to send a socket with a network event when detecting a socket. The message to the user is designated by the user; the network event is set by the parameter Levent. Call this file take the initiative to set the socket to a non-blocking mode. Levent's value can be the following "OR" portfolio: (see Winsock No. 1.1 88, 89) FD_READ, FD_WRITE, FD_OOB, FD_ACCEPT, FD_CONNECT, FD_CLOSE User If you call this one again for a socket, you will cancel it. The original settings for this socket. To cancel all settings to the socket, the value of the LEVEN must be set to 0.

(Figure 2) WSAASYNCSELECT Funny Parameters and Application Relationship We ask the Winsock system to know when the client is coming to connect, send an async_event message to the hwnd this window; because we want to know only an Accept event, so we only Set the fd_accept. WSAAsyncselect (Listen_SD, HWND, Async_Event, FD_ACCEPT) (Figure 3) Demoserv establishes socket on a Winking system and enters the listening status reader must pay attention to a point, the setting of WSaasyncselect is aimed at "a socket"; otherwise, only when you set up You will receive this message (async_event) when the event (FD_ACCEPT) of this socket (Listen_SD) occurs. If you open a lot of sockets, let each socket turn to Asynchronous mode, then you must set WSaAsyncselect to the "Every Socket". And if you want to set a Socket's Async event notification, then use WSaasyncselect this file; and the fourth parameter Levent must be set to 0. WSaasyncselect (s, hwnd, 0, 0) - Cancel all ASYNC event settings Here I want to tell you, call WSAAsyncSelect, while also changing this socket into a "non-blocking) mode. But at this time, this Socket does not simply use the ioctlsocket () to change it back to the "Blocking" mode. That is, the "non-blocking" mode changed by WSaasyncselect and IOCTLSocket is still different. If you want to change a "Asynchronous mode" Socket ", you must call WSAAsyncSelect () to cancel all Async events, then use ioctlsocket () to turn it back to block mode. IOCTLSOCKET (): Controls the mode of the socket. Format: Int Pascal Far IOCTLSOCKET (Socket S, Long CMD, U_LONG FAR * Argp); Parameters: S Socket Identification Code CMD Directive Name Argp Number Parametric Passage Revitalization: Success - 0 Failed - Socket_ERROR (Call WsageTlasterror () Releaseable Cause) Description: This file is used to get or set the operation parameters of the socket.

The instructions provided are: (See Winsock Item 1.1 35, 36) CMD's value: Fionbio - Switch Non-Blocking mode FionRead - Since Socket readable data (current In Buffer information) Quantity) Siocatmark - OOB Did it have been read because the SOCKET of our Server end is used in non-synchronous mode, and the FD_ACCEPT event is set, so when the Client side is connected to us, Winsock Stack will actively inform us; let's first Let's see how the Client side is connected to the Server end? [Client side actively establishes the connection] Client first is also a call wsastartup () in a copy to establish a relationship with the Winsock Stack; then call socket () to create a TCP Socket. (Reader must use TCP Socket to connect to the Server's TCP Socket without using UDP socket; because the Sockets of the same agreement can be connected, TCP is different from the UDP) and the SOCKET of the Server end: Client The end of the socket can call the bind () in, specify the IP address and the PORT number; however, you can do not call Bind (), and the Winsock Stack is powered by the IP address and the PORT number (this action is in call The consNect () is complete by the Winsock system). Usually we don't call bind (), and by the system, you can call the getSockName () in the GetSockName () to check the system to help us set what IP and Port. In general, the system will automatically help us set between 1024 to 5000; and if the reader wants to set the port with BIND, it is best to 5000 or more numbers. Connect (): Requires a TCP Socket to the specified other party. Format: Int Pascal Far Connect (Socket S, Const Struct Sockaddr Far * Name, Int Namelen); Paramese: s Socket Identification Code Name This Socket wants to connect to the diamelelen name of Namelen Name: Success - 0 failed - Socket_ERROR (Call Wsagetlasterror () can be learned) Description: This file is used to establish a connection to the other party. If the specified object address is 0, it will pass the wrong mistake. When the connection is completed, the user can use this socket to do the use of transfer or reception. In our example, the client is to connect to the 7016 PORT listening to the Server on the machine, so we have the following frames.

(Suppose our machine's IP has my_host_ip) strunt sockaddr_in sa; / * variable declaration * / sa.sin_family = PF_INET; / * Set the Server-end data to be connected * / sa.sin_port = htons (7016); sa.sin_addr. S_addr = htonl (my_host_ip); Connect (mysd, (Struct SockAddr Far *) & sa, sizeof (sa)) / * Establish connection * / [server-side connection] Since the SOCKET of our Server is set to "non-synchronization Mode ", and is for FD_ACCEPT events, so when the client is connected, the HWND of our Server end will receive a message from an async_event sent by Winsock Stack. (See the settings of WSAAsyncselect "At this time, we should use wsagetSelectEverror (LPARAM) to check if there is an error; Many events, but only one message is used to represent) (here is of course FD_ACCEPT event); then call the related functions to handle this event. So we call an Accept () in a function to create a connection to the Server end. Accept (): Accepts a Socket connection requirement to complete the connection of the Stream Socket. Format: Socket Pascal Far Accept (Scoket S, Struct Sockaddr Far * Addr, INT FAR * ADDRLEN); Parameters: s S socket identification code addr storage connection to the end of the address AddRlen Addr length passive: Success - new Socket identification code failed - INVALID_SOCKET (Call Wsagetlasterror () Reason: The application of the Server end calls this one-word to accept the Socket connection action required by the Client side; if the SOCKET of the Server is the Blocking mode, and no People ask a connection action, then this is the block; if it is a non-blocking mode, this file will reply immediately. ACCEPT () The reply value of a function is a new socket, which is not reusable to accept other connection requirements; but the SOCKET originally listened can still accept other people's connection requirements. The Server end of TCP Socket After calling accept (), it will return a new Socket number; this new Socket number is the Socket that is truly communicating with the Client side.

For example, we have established a TCP Socket with socket (), and this Socket number (system given) is 1, then we call Bind (), listen (), accept () is a stenet; After calling accept (), the return value is another Socket number (it is also a system), such as 3; then, the number 3; 3 Socket, we collect the information, we also use Socket 3, not Socket 1; readers should not make mistakes. Our calls in the program are as follows; we can pass the second parameter to the value, know which IP address and the port number of the Port number are connected to our Server. Struct SockAddr_in sa; int sa_len = sizeof (sa); my_sd = accept (Listen_SD, (Struct Sockaddr Far *) & SA, & SA_LEN) When the Server end is completed, the main TCP Socket connection is really established. The server and client ends can also use this socket to send information to the other party or to the other party. (Related to the information of the information, let's talk about the next phase) (Figure 4) Demoserv and DemoCLNT After the connection is successful, the SOCKET connection is ended in Winking] Finally, let's take a look at how to end the socket connection. Socket is close and simple, and can be started first by any end of Server or Client, as long as CLOSESOCKET () can be called. To turn off the Socket of the listening state, it is also use this one. CloseSocket (): Close a socket. Format: Int Pascal Far CloseSocket (Socket S); Parameters: S Socket Identification Code Passage Passage: Success - 0 Failed - Socket_ERROR (Call WsageTlasterror () Receptes: This one is used to close some Socket. If the user originally sets SO_DONTLINGER to the SOCKET to be turned off, it will reply immediately after calling this one, but this SOKCET has not been transferred after the data will continue after it will be closed. If the user originally set this socket as SO_Linger, there are two cases: (a) Timeout is set to 0, this Socket is reset immediately, and the not received or the unrecovered information is lost. (b) Timeout is not 0, it will be sent, or wait until TIMEOUT will really turn off. Before the end of the program, don't forget to call WSACleanup () to inform Winsock Stack; if you don't call this one, some resources may still be occupied by you and cannot be removed. WSACLEANUP (): End the use of Windows Sockets DLL.

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

New Post(0)