Research on Winsock API Based on Visual C ++ (1)

Source: Internet
Author: User
To facilitate network programming, Microsoft and several other companies jointly developed a set of network programming interfaces for windows in Early 1990s, namely, the Windows Sockets specification, which is not a network protocol, it is an open network programming interface in Windows that supports multiple protocols. Currently, Winsock has basically implemented protocol-independent functions. You can use Winsock to call the functions of multiple protocols, but the TCP/IP protocol is usually used. The socket actually provides a communication port in the computer, which can be used to communicate with any computer with a socket interface. Applications are transmitted over the network and the received information is implemented through this socket interface.

Microsoft defines Winsock classes for VC, such as casyncsocket and csocket classes born in casyncsocket. They are easy to use. Readers can certainly use these classes to implement their own network programs, however, in order to better understand Winsock API programming technology, we will discuss how to use underlying API functions to implement simple Winsock network application programming, and explain how to operate sockets on the server and client respectively, realize data transmission based on TCP/IP, and finally provide the relevant source code.

When developing Winsock APIs in VC, you must use the following three files in the project. Otherwise, a compilation error occurs.

1. Winsock. H: This is the header file of Winsock API and must be included in the project.

2. wsock32.lib: Winsock API Connection Library file. In use, it must be included in the project file as a non-default Connection Library of the project.

3. Winsock. dll: the dynamic Connection Library of WinSock, which is located in the installation directory of windows.

I. socket operations on the server)

1) Call wsastartup () during initialization ()

This function initializes Windows Sockets DLL in the application. Only after this function is successfully called can the application call other APIs in Windows Sockets DLL. The following code calls a function in a program: wsastartup (Word) (1 <8 | 1), (lpwsadata) & wsadata ), (1 <8 | 1) indicates that we use winsocket1.1, and wsaata is used to store winsocket information returned by the system.

2) Establish a socket

After initializing the Winsock dynamic connection library, you need to establish a listening socket on the server side. Therefore, you can call the socket () function to establish the socket for this listener, define the communication protocol used by the socket. If this function is called successfully, a socket object is returned. If the function fails, invalid_socket (wsagetlasterror () is called to find the cause. All winsocket functions can use this function to obtain the cause of the failure ).

Socket Pascal far socket (int af, int type, int Protocol)

Parameter: AF: currently, only pf_inet (af_inet) is provided );

Type: socket type (sock_stream, sock_dgram );

Protocol: Communication Protocol (set to 0 if not specified by the user );

If you want to establish a socket that complies with the TCP/IP protocol, the second parameter type should be sock_stream. For example, the socket that is UDP (datagram) should be sock_dgram.

3) bind the port

Next, you need to specify an address and port for the socket of the listener defined by the server so that the client can know which port to connect, therefore, we need to call the BIND () function. If this function is successfully called, 0 is returned; otherwise, socket_error is returned.

Int Pascal far BIND (socket S, const struct sockaddr far * Name, int namelen );

Parameter: S: Socket Object Name;

Name: the socket address value, which must be the IP address of the machine on which the program is executed;

Namelen: Name Length;

If you do not care about the address or port value, you can set the address to inaddr_any and port to 0, windows Sockets automatically sets the appropriate address and port (value between 1024 and 5000 ). Then you can call the getsockname () function to obtain the set value.

4) Listen

After the socket object on the server is bound, the server must establish a listener queue to receive client connection requests. The listen () function enables the socket on the server to enter the listening status, and sets the maximum number of connections that can be established (currently the maximum value is 5 and the minimum value is 1 ). If this function is successfully called, 0 is returned; otherwise, socket_error is returned.

Int Pascal far listen (socket S, int backlog );

Parameter: s: the socket to be monitored;

Backlog: Maximum number of connections;

After the server socket calls listen (), if the client calls the connect () function to apply for a connection, the server must call the accept () function again, in this way, the connection between the server and the client is deemed to have officially completed the communication program. In order to know when the client puts forward connection requirements, so that the socket on the server can call the accept () function to establish the connection at the right time, we need to use the wsaasyncselect () function, let the system send a connection request to a client. If this function is successfully called, 0 is returned; otherwise, socket_error is returned.

Int Pascal far wsaasyncselect (socket S, hwnd, unsigned int wmsg, long Levent );

Parameter: S: Socket object;

Hwnd: the handle to receive messages;

Wmsg: the message sent to the window;

Levent: A registered network event, that is, a network event in which an application sends messages to a window. The value is a combination of the following values: fd_read, fd_write, fd_oob, fd_accept, fd_connect, and fd_close, the specific meaning of each value is fd_read: You want to receive a message when receiving data from socket s; fd_write: You want to receive a message when sending data on socket s; fd_accept: to receive a message when receiving a connection request on socket s; fd_connect: to receive a message when the connection on socket S is successful; fd_close: to receive a message when the connection on socket S is closed; fd_oob: if you want to receive out-of-band data on socket S, you will receive the message.

For specific applications, wmsg should be the message name defined in the application, while lparam in the message structure is the name of the above network events. Therefore, you can use the following structure in the window processing custom message functions to respond to different Socket events:

Switch (lparam)

{Case fd_read:

...

Break;

Case fd_write,

...

Break;

...

}

5) The Server accepts client connection requests

When the client initiates a connection request, the hwnd window on the server receives a custom message from Winsock stack. In this case, we can analyze lparam and call related functions to handle this event. To enable the server to accept client connection requests, you must use the accept () function. This function creates a new socket that communicates with the client's socket. The socket originally listened to continues to enter the listening status, wait for others' connection requirements. If this function is successfully called, a new socket object is returned; otherwise, invalid_socket is returned.

Socket Pascal far accept (scoket S, struct sockaddr far * ADDR, int far * addrlen );

Parameter: S: Socket identifier;

ADDR: the address of the client to be connected;

Addrlen: length of ADDR

6) End the socket connection

It is very easy to end the communication connection between the server and the client. This process can be started at either end of the server or client. You only need to call closesocket, this function is also used to disable the socket in the server listening status. In addition, it corresponds to the number of wsastartup () threads called during program startup. Before the program ends, you need to call wsacleanup () to notify Winsock stack to release the resources occupied by the socket. If both functions are called successfully, 0 is returned; otherwise, socket_error is returned.

Int Pascal far closesocket (socket S );

Parameter: S: Socket identifier;

Int Pascal far wsacleanup (void );

Parameter count: None

(From http://soft6.com/tech/8/89107.html)

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.