Sample - Simple Client/Server Connection
Using Sockets (Client): Notes Code
#include "winsock2.h" //#include "winsock2.h" (ws2_32.lib)
#include "iostream.h" //cout
#define IP_ADDRESS "127.0.0.1"
#define PORT_NUMBER 10000
void main()
{
WSADATA wsaData;
WSAStartup( MAKEWORD( 2, 0), &wsaData );
SOCKET st = socket( PF_INET, SOCK_STREAM, 0 );
if ( st == INVALID_SOCKET )
{
cout << "Invalid Socket" << endl;
cout << WSAGetLastError() << endl;
}
u_long lBinaryIP =inet_addr( IP_ADDRESS );
u_short iNetworkPort = htons( PORT_NUMBER );
SOCKADDR_IN sinServer;
sinServer.sin_family = AF_INET; //PF_NET for WinSock 1.1 only!
sinServer.sin_addr.s_addr = /*INADDR_ANY*/ lBinaryIP;
sinServer.sin_port = iNetworkPort;
/***************************************************************************
* Code above is identical for client and server. Now client calls connect *
* ( server called bind and listen at this point) *
****************************************************************************/
int iStatus = connect( st, (LPSOCKADDR)&sinRemote, sizeof(SOCKADDR_IN) );
if( iStatus == SOCKET_ERROR )
{
cout << "Connect Error" << endl;
cout << WSAGetLastError() << endl;
}
else
{
cout << "Connect Passed ..." << endl;
}
/***************************************************************************
* Client reads a message from server by calling recv (short of receive) *
****************************************************************************/
char szReceiveString[100];
iStatus = recv( st,
szReceiveString,
sizeof(szReceiveString),
0 /*recommended*/);
if( iStatus == SOCKET_ERROR )
{
cout << "Receive Error" << endl;
cout << WSAGetLastError() << endl;
}
else
{
cout << szReceiveString << endl;
}
WSACleanup();
}
2002, Netston Consulting