WinSock network programming BASICS (3) server and winsock network programming

Source: Internet
Author: User

WinSock network programming BASICS (3) server and winsock network programming

In the previous article, we talked about the implementation of a simple client for sending data. Next we will talk about how to send and receive data servers.
The server mentioned here is actually a process. It needs to wait for any number of clients to establish a connection with it to respond to their requests.

The server must listen for connections with known names (the IP address and port number are in TCP/IP, and the addressing scheme and naming method of different protocols are also different)

 

The first step to create a server program is the same as that of the client. initialize and create a SOCKET (LISTENSOCKET is used to listen to client connections)
#define DEFAULT_PORT "27015"struct addrinfo *result = NULL, *ptr = NULL, hints;ZeroMemory(&hints, sizeof (hints));hints.ai_family = AF_INET;hints.ai_socktype = SOCK_STREAM;hints.ai_protocol = IPPROTO_TCP;hints.ai_flags = AI_PASSIVE;// Resolve the local address and port to be used by the serveriResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);if (iResult != 0) {    printf("getaddrinfo failed: %d\n", iResult);    WSACleanup();    return 1;}SOCKET ListenSocket = INVALID_SOCKET;ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);if (ListenSocket == INVALID_SOCKET) {    printf("Error at socket(): %ld\n", WSAGetLastError());    freeaddrinfo(result);    WSACleanup();    return 1;}

  

 

The listening address set for the socket here is AF_INET, that is, the IPv4 address. If you want to listen to IPv6 addresses, you can set it to AF_INET6. If you want to listen to IPv6 addresses at the same time, you need to create two listening sockets, (vista later provides a special socket that can listen to both IPv4 and IPv6. Details: Dual-Stack Sockets)

 

Next we need to bind the socket to its known address (IP address and port)
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);if (iResult == SOCKET_ERROR) {        printf("bind failed with error: %d\n", WSAGetLastError());        freeaddrinfo(result);        closesocket(ListenSocket);        WSACleanup();        return 1;}freeaddrinfo(result); 

  

Bind function:

Int bind (_ In _ SOCKET s, // wait for the SOCKET _ In _ const struct sockaddr * name, // point to the bound address structure _ In _ int namelen // indicates the length of the address structure determined by the Protocol );

Once an error occurs in binding, bind returns SOCKET_ERROR. The most common error for bind is WSAEADDRINUSE (indicating that another process has been bound to the local ip address and port number, or that the ip address and port number are in the TIME-WAIT Status) and WSAEFAULT (the called socket has been bound)

After the bind function is called, the address information returned by the getaddrinfo function is useless. You can use freeaddrinfo to release the address information.

 

Next, set the socket to the listening mode:
if ( listen( ListenSocket, SOMAXCONN ) == SOCKET_ERROR ) {    printf( "Listen failed with error: %ld\n", WSAGetLastError() );    closesocket(ListenSocket);    WSACleanup();    return 1;}

  

Listen function:

Int listen (_ In _ SOCKET s, // The number of unprocessed connections allowed by the bound SOCKET _ In _ int backlog // The maximum number of connections allowed In the listener Queue );

The backlog parameter is very important. It specifies the maximum queue length of the shelved connection (for example, the backlog parameter is 3, but four clients send requests at the same time, the first three will be placed in the suspended queue, and the fourth will fail to connect to the request and return the WSAECONNREFUSED error)

Now we can accept the customer service connection:
SOCKET ClientSocket;ClientSocket = INVALID_SOCKET;ClientSocket = accept(ListenSocket, NULL, NULL);if (ClientSocket == INVALID_SOCKET) {    printf("accept failed: %d\n", WSAGetLastError());    closesocket(ListenSocket);    WSACleanup();    return 1;}

  

The accept function will return a new socket descriptor, which corresponds to a connection that has accepted the client. Subsequent operations on the client will use the new socket, while the original LinstenSocket is still in the listening mode:

SOCKET accept (_ In _ SOCKET s, // a SOCKET _ Out _ struct sockaddr * addr In listening mode, // a pointer to the sockaddr_in structure, used to obtain the address information of the other party _ Inout _ int * addrlen // length of the addr structure );

 

After accepting the connection from the client, the RECV and SEND functions are used to receive and SEND data.
#define DEFAULT_BUFLEN 512char recvbuf[DEFAULT_BUFLEN];int iResult, iSendResult;int recvbuflen = DEFAULT_BUFLEN;do {    iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);    if (iResult > 0) {        printf("Bytes received: %d\n", iResult);        iSendResult = send(ClientSocket, recvbuf, iResult, 0);        if (iSendResult == SOCKET_ERROR) {            printf("send failed: %d\n", WSAGetLastError());            closesocket(ClientSocket);            WSACleanup();            return 1;        }        printf("Bytes sent: %d\n", iSendResult);    } else if (iResult == 0)        printf("Connection closing...\n");    else {        printf("recv failed: %d\n", WSAGetLastError());        closesocket(ClientSocket);        WSACleanup();        return 1;    }} while (iResult > 0);

  

 

After the communication is complete, disconnect:
iResult = shutdown(ClientSocket, SD_SEND);if (iResult == SOCKET_ERROR) {    printf("shutdown failed: %d\n", WSAGetLastError());    closesocket(ClientSocket);    WSACleanup();    return 1;}closesocket(ClientSocket);WSACleanup();

  

 

Complete server Source Code:

# Ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # include <windows. h> # include <WinSock2.h> # include <WS2tcpip. h> # include <IPHlpApi. h> # include <stdio. h> # pragma comment (lib, "Ws2_32.lib") // # pragma comment (lib, "Mssock. lib ") // # pragma comment (lib," Advapi32.lib ") # define DEFAULT_PORT" 27015 "# define DeFAULT_BUFLEN 512int main () {WSADATA wsaData; int iResult; int iSendResult; struct addrinfo * result = NULL; struct addrinfohints; char recvbuf [empty]; int recvbuflen = empty; SOCKET ListenSocket = INVALID_SOCKET; SOCKET ClientSocket = INVALID_SOCKET; iResult = WSAStartup (MAKEWORD (2, 2 ), & wsaData); if (iResult! = 0) {printf ("WSAStartup failed: % d \ n", iResult); return 1;} ZeroMemory (& hints, sizeof (hints); hints. ai_family = AF_INET; hints. ai_socktype = SOCK_STREAM; hints. ai_protocol = IPPROTO_TCP; hints. ai_flags = AI_PASSIVE; // determine the local address and port iResult = getaddrinfo (NULL, DEFAULT_PORT, & hints, & result) for the server; if (iResult! = 0) {printf ("getaddrinfo failed: % d \ n", iResult); WSACleanup (); return 1 ;}listensocket = socket (result-> ai_family, result-> ai_socktype, result-> ai_protocol); if (ListenSocket = INVALID_SOCKET) {printf ("socket failed with error: % ld \ n", WSAGetLastError ()); freeaddrinfo (result); WSACleanup (); return 1;} iResult = bind (ListenSocket, result-> ai_addr, (int) result-> ai_addrlen); if (iResult = SOCKET_ERROR) {printf ("bind failed with error: % d \ n", WSAGetLastError (); freeaddrinfo (result); closesocket (ListenSocket); WSACleanup (); return 1 ;} freeaddrinfo (result); iResult = listen (ListenSocket, SOMAXCONN); if (iResult = SOCKET_ERROR) {printf ("Listen failed with error: % d \ n ", WSAGetLastError (); closesocket (ListenSocket); WSACleanup (); return 1;} ClientSocket = accept (ListenSocket, NULL, NULL); if (ClientSocket = INVALID_SOCKET) {printf ("accept failed: % d \ n", WSAGetLastError (); closesocket (ClientSocket); WSACleanup (); return 1;} closesocket (ListenSocket ); do {iResult = recv (ClientSocket, recvbuf, recvbuflen, 0); if (iResult> 0) {printf ("Bytes encoded ed: % d \ n", iResult ); iSendResult = send (ClientSocket, recvbuf, iResult, 0); if (iSendResult = SOCKET_ERROR) {printf ("send failed: % d \ n", WSAGetLastError ()); closesocket (ClientSocket); WSACleanup (); return 1;} printf ("Bytes sent: % d \ n", iSendResult);} else if (iResult = 0) {printf ("Connection closing... \ n ") ;}else {printf (" recv failed: % d \ n ", WSAGetLastError (); closesocket (ClientSocket); WSACleanup (); return 1 ;}} while (iResult> 0); // disconnect iResult = shutdown (ClientSocket, SD_SEND); if (iResult = SOCKET_ERROR) {printf ("shutdown failed: % d \ n ", WSAGetLastError (); closesocket (ClientSocket); WSACleanup (); return 1 ;}// clear the printf connection ("recv message: % s", recvbuf); closesocket (ClientSocket ); WSACleanup (); return 0 ;}

  

Link: http://www.bugcoding.com/entry/11

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.