VC ++ network socket programming

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.

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), where (1 <8 | 1) indicates that we use winsocket1.1, 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 ).
Int socket (int af, int type, int Protocol );
Socket 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 BIND (socket S, const struct sockaddr * 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) obtain remote host information

The function accepts the host domain name in the form of XXX. yyy. Zzz;
Call DNS and return a pointer to the hostent structure.
Function prototype:
Struct hostent * gethostbynme (const char * hostname );
Struct hostent {
Char * h_name; // pointer to the Host Name
Char ** h_aliases; // pointer to the pointer array. Each pointer in the array can point to an alias that can be called by the host.
Int h_addrtype; // address type, (af_inet in the Internet)
Int h_length; // address Length
Char ** h_addr_list; // pointer to the pointer array, and each pointer in the array points to one of the host addresses.
};

5) Connection

The connect function is used by a process to establish a connection with a remote process.
Prototype int connect (socket S, const struct sockaddr * servname, int servnamelen)
Parameter: S: Socket Object Name; servname: Remote socket address value; server address;
Servnamelen: length of servname;

6) 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 listen (socket S, int backlog );
Parameter: s: the socket for the listener needs to be created;
Backlog: Maximum number of connections;

7) accept

The accept function is scheduled by the TCP server to remove the first connection request from the corresponding queue. If no request is sent, the accept function is set to sleep.
Function prototype socket
Accept (socket S, const struct sockaddr * clientaddr, int * clientaddrlen );
This function actually creates a new plug-in, and the sub-server can use it to connect to this customer.

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.
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:

9) 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.

10) 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 calling the wsastartup () function when the program starts. 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.

 

Client Program:


1) create a socket for the client


The client application first calls the wsastartup () function to establish a relationship with Winsock's dynamic connection library, and then calls socket () to establish a TCP or UDP socket (the same protocol can communicate with each other, TCP to TCP, UDP to UDP ). Different from the socket on the server, the client socket can call the BIND () function to specify the IP address and port number, but it can also not call BIND (), winsock automatically sets the IP address and port number.

2) Submit a connection Application


The client socket uses the connect () function to apply for a connection with the server socket. If the function call succeeds, 0 is returned; otherwise, socket_error is returned.
Although the TCP/IP-based connection protocol (stream socket) service is the mainstream standard for designing client/server applications, some services can also use the connectionless protocol (datagram socket) provided. First, we will introduce the features of TCP socket and UDP socket when transmitting data: stream (TCP) socket provides bidirectional, reliable, ordered, and non-repeated data transmission.
Although datax (UDP) socket provides two-way communication, it is not reliable, ordered, and non-repetitive. Therefore, UDP data transmission may receive unordered and duplicated data, even data is missing during transmission.
Because UDP socket does not guarantee that the data can be completely delivered to the other party during data transmission, most applications use TCP to process the socket to ensure the correctness of the data. Generally, the send and receive functions of the TCP socket call the send () and Recv () functions, while the UDP socket uses sendto () and recvfrom () functions () these two functions call the length of the data sent or received. Otherwise, socket_error is returned.
For datax socket, if the size of datax exceeds the limit, no data is sent and an error value is returned. For stream socket, in blocking mode, if the storage space in the transmission system is insufficient to store the data to be transmitted, send () will be blocked until the data is delivered; if the socket is set to the non-blocking mode, the data will be sent based on the current output buffer space and will not be blocked. The flags value can be set to a combination of 0, msg_dontroute, and MSG_OOB.
For stream socket, we can receive valid data in the current input buffer, but its quantity cannot exceed the Len size. Based on the above knowledge, I have customized a simple cmysocket class. Below is some implementation code of the class I have defined:
With the definition of the above class, you can define the cmysocket object on the server and client of the Network Program, establish a connection, and transmit data. For example, in order to send data on the server and client, two cmysocket objects, serversocket1 and serversocket2, must be defined on the server side for listening and connection. The client defines a cmysocket object, clientsocket, it is used to send or receive data. If the number of established connections is greater than one, you can define a cmysocket object on the server. Note that the number of connections must not exceed five.

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.