Winsock Learning 1: the server that uses WinSock to implement socket communication.

Source: Internet
Author: User
Tags htons

Learn about the Winsock API and refer to the server example in the book.

The source code is as follows:

/*
* File: Server. cpp
*
*/

# Include <winsock2.h>
# Include <stdio. h>
# Include <stdlib. h>

# Define default_port 5150.
# Define default_buffer 4096.
Int iport = default_port;

Bool binterface = true;
Bool brecvonly = false;
Char szaddress [128];
// Function: Usage
// Description:
// Print usage information and exit
Void usage ()
{
Printf ("Usage: Server [-P: X] [-I: IP] [-O]/n ");
Printf ("-P: X port number to listen on/N ");
Printf ("-I: Str interface to listen on/N ");
Printf ("-O dont't echo the data back/N ");
Printf ("Camel 2004-8-29 ");
Exitprocess (1 );
}

// Function:
Void validateargs (INT argc, char ** argv)
{
Int I;
For (I = 1; I <argc; I ++)
{
If (argv [I] [0] = '-') | (argv [1] [0] = '/'))
{
Switch (tolower (argv [I] [1])
{
Case 'p ':
Iport = atoi (& argv [I] [3]);
Break;
Case 'I ':
Binterface = true;
If (strlen (argv [I])> 3)
Strcpy (szaddress, & argv [I] [3]);
Break;
Case 'O ':
Brecvonly = true;
Break;
Default:
Usage ();
Break;
}
}
}

}

//
DWORD winapi clientthread (lpvoid lpparam)
{
Socket sock = (socket) lpparam;
Char szbuff [default_buffer];
Int ret,
Nleft,
Idx;
While (1)
{
// Perform a blocking Recv () call
Ret = Recv (sock, szbuff, default_buffer, 0 );
If (ret = 0) // graceful close
Break;
Else if (ret = socket_error)
{
Printf ("Recv () failed: % d/N", wsagetlasterror ());
Break;
}
Szbuff [RET] = '/0 ';
Printf ("Recv: '% s'/N", szbuff );
//
// If we selected to echo the data back, do it
//
If (! Brecvonly)
{
Nleft = ret;
Idx = 0;
//
// Make sure we write all the data
//
While (nleft> 0)
{
Ret = Send (sock, & szbuff [idx], nleft, 0 );
If (ret = 0)
Break;
Else if (ret = socket_error)
{
Printf ("Send () failed: % d/N", wsagetlasterror ());
Break;
}
Nleft-= ret;
Idx + = ret;

}
 
}

}
Return 0;

}

Int main (INT argc, char ** argv)
{
Printf ("server. CPP/N ");
Wsadata WSD;
Socket slisten,
Sclient;
Int iaddrsize;
Handle hthread;
DWORD dwthreadid;
Struct sockaddr_in local, client;
Validateargs (argc, argv );
If (wsastartup (makeword (2, 2), & WSD )! = 0)
{
Printf ("failed to load Winsock! /N ");
Return 1;
}
//
// Create out listening socket
//
Slisten = socket (af_inet, sock_stream, ipproto_ip );
If (slisten = socket_error)
{
Printf ("socket () failed: % d/N", wsagetlasterror ());
Return 1;
}
// Select the local interface, and bind to it
//
If (binterface)
{
Local. sin_addr.s_addr = inet_addr (szaddress );
If (local. sin_addr.s_addr = inaddr_none)
Usage ();
}
Else
Local. sin_addr.s_addr = htonl (inaddr_any );
Local. sin_family = af_inet;
Local. sin_port = htons (iport );

If (BIND (slisten, (struct sockaddr *) & Local, sizeof (local) = socket_error)
{
Printf ("Bing () failed: % d/N", wsagetlasterror ());
Return 1;
}
Listen (slisten, 8 );
//
// In a continuous loop, wait for incoming clients. Once one
// Is detected, create a thread and pass the handle off to it.
//
While (1)
{
Iaddrsize = sizeof (client );
Sclient = accept (slisten, (struct sockaddr *) & client, & iaddrsize );
If (sclient = invalid_socket)
{
Printf ("accept () failed: % d/N", wsagetlasterror ());
Break;
}
Printf ("accepted client: % s: % d/N", inet_ntoa (client. sin_addr), ntohs (client. sin_port ));

Hthread = createthread (null, 0, clientthread, (lpvoid) sclient, 0, & dwthreadid );
If (hthread = NULL)
{
Printf ("createthread () failed: % d/N", getlasterror ());
Break;
}
Closehandle (hthread );

}
Closesocket (slisten );
Wsacleanup ();

Return 0;
}

//--------------------------------------------------------

When compiling in VC ++ 6.0, It is not familiar with the VC ++ compiler. Open

An error occurred while parsing the function name in the Winsock API.

...

Error lnk2001: unresolved external symbol _ inet_addr @ 4
Error lnk2001: unresolved external symbol _ htons @ 4
Error lnk2001: unresolved external symbol _ socket @ 12
...

Add ws2_32.lib to the project.

Project --> setting --> link --> Object/library modules add ws2_32.lib

 

 

 

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.