Click here to Skip to main content
15,879,348 members
Articles / Desktop Programming / MFC

Server Client Sockets

Rate me:
Please Sign up or sign in to vote.
4.76/5 (84 votes)
25 Apr 20039 min read 488.6K   15.2K   192  
Sample application Uses Server and client socket to establish exchange of data
#include <iostream>
#include <winsock.h>
#include <windows.h>
#include <string>

using namespace std;

#define SERVER_SOCKET_ERROR 1
#define SOCKET_OK 0

#pragma comment(lib, "wsock32.lib")

void socketError(char*);

int main()
{
	WORD sockVersion;
	WSADATA wsaData;
	int rVal;

	sockVersion = MAKEWORD(1,1);
	//start dll
	WSAStartup(sockVersion, &wsaData);

	//create socket
	SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

	if(s == INVALID_SOCKET)
	{
		socketError("Failed socket()");
		WSACleanup();
		return SERVER_SOCKET_ERROR;
	}

	//fill in sockaddr_in struct 

	SOCKADDR_IN sin;
	sin.sin_family = PF_INET;
	sin.sin_port = htons(8888);
	sin.sin_addr.s_addr = INADDR_ANY;

	//bind the socket
	rVal = bind(s, (LPSOCKADDR)&sin, sizeof(sin));
	if(rVal == SOCKET_ERROR)
	{
		socketError("Failed bind()");
		WSACleanup();
		return SERVER_SOCKET_ERROR;
	}

	//get socket to listen 
	rVal = listen(s, 2);
	if(rVal == SOCKET_ERROR)
	{
		socketError("Failed listen()");
		WSACleanup();
		return SERVER_SOCKET_ERROR;
	}

	//wait for a client
	SOCKET client;
	
	cout << "waiting for newclient" << endl;

	client = accept(s, NULL, NULL);

	cout << "newclient found" << endl;

	if(client == INVALID_SOCKET)
	{
		socketError("Failed accept()");
		WSACleanup();
		return SERVER_SOCKET_ERROR;
	}

	char buf[4]; 
	rVal = recv(client, buf, 4, 0);

	if(rVal == SOCKET_ERROR)
	{
		//delete [] buf;
		int val = WSAGetLastError();
		if(val == WSAENOTCONN)
		{
			cout << "socket not connected" << endl;
		}
		else if(val == WSAESHUTDOWN )
		{
			cout << "socket has been shot down!" << endl;
		}
		socketError("Failed recv()");
		return SERVER_SOCKET_ERROR;
	}
	string data(buf);

	//delete [] buf;

	cout << "Recived(data)>"<< buf << endl;

	//close process
	closesocket(client);
	closesocket(s);

	WSACleanup();

	return SOCKET_OK;
};

void socketError(char* str)
{
	MessageBox(NULL, str, "SERVER SOCKET ERROR", MB_OK);
};

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions