Winsock Network Programming Fundamentals (3) server

Source: Internet
Author: User

The previous article was about the simple implementation of the client that sent the data. The next step is how to implement a data server for sending and receiving.
The server here is actually a process that waits for any number of clients to establish a connection to respond to their requests.

The server must listen for a connection on a known name (IP address and port number in TCP/IP, different protocol addressing scheme and naming method)

The first step in creating a server program is to initialize and create the socket (Listensocket is used to listen for client connections) just like the client.
#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 being used by the Serveriresult = Getaddrinf O (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 socket setting here is af_inet, which is the address of IPv4. If you want to listen to the IPV6 address can be set to Af_inet6, if you want to listen at the same time need to create two listening sockets, (Vista system provides a special socket to listen to both IPV4 and IPV6. Details: Dual-stack Sockets)

Next you need to bind the socket to its known address (IP 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 ();        

  

Bind function:

int bind (  _in_ socket s,//socket waiting for Client connection  _in_ const struct SOCKADDR *name,//point to binding address structure  _in_ int Namelen//representation The length of the address structure to be passed, as determined by the Protocol);

Once bind is faulted, BIND returns SOCKET_ERROR. The most common error for bind is Wsaeaddrinuse (indicating that another process has been bound to the local IP and port number, or that the IP and port number is in the time--wait state) and Wsaefault (the calling socket is already bound)

After the bind function is called, the address information returned by the Getaddrinfo function is basically not useful, and you can use Freeaddrinfo to release the address information.

The next thing to do is to set the socket to listen 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,//bound socket  _in_ int backlog//listening queue allows to keep the maximum number of connections that have not been processed);

Backlog This parameter is important, it specifies the maximum queue length of the attached connection (for example, the backlog parameter is 3, but 4 clients make the request at the same time, the first 3 are placed in the Suspended queue, and the fourth connection request fails to return a wsaeconnrefused error)

Now we can accept the connection of the customer service side:
SOCKET Clientsocket; Clientsocket = Invalid_socket; Clientsocket = Accept (listensocket, NULL, NULL), if (Clientsocket = = invalid_socket) {    printf ("Accept failed:%d\n", W Sagetlasterror ());    Closesocket (listensocket);    WSACleanup ();    return 1;}

  

The Accept function returns a new socket descriptor that corresponds to a connection that has already accepted the client, and the client's subsequent operations use the new socket, while the original Linstensocket is still in listening mode:

Socket accept (  _in_ socket S,//a socket for listening mode  _out_ struct sockaddr *addr,//A pointer to the SOCKADDR_IN structure for obtaining the address information of the other party  _inout_ int *addrlen The length of the//ADDR structure);

After accepting the client connection, the data is received using the recv and send functions
#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);

  

Communication 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 ();

  

Full 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[default_buflen];int recvbuflen = Default_buflen; 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;//determines the local address and port for the server Iresult = getaddrinfo (NULL, Default_port, &hints, & Result), 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-&GT;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);d o {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);//Disconnect Iresult = Shutdown (clientsocket, sd_send), if (Iresult = = socket_error) {printf ("Shutdown FAI LED:%d\n ", WSAGetLastError ()); closesocket (Clientsocket); WSACleanup (); return 1;} Clean connection printf ("recv message:%s", recvbuf); closesocket (Clientsocket); WSACleanup (); return 0;}

  

Original link: HTTP://WWW.BUGCODING.COM/ENTRY/11

Winsock Network Programming Fundamentals (3) server

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.