Click here to Skip to main content
13,202,706 members (55,590 online)
Click here to Skip to main content

Stats

408.3K views
13.3K downloads
186 bookmarked
Posted 25 Apr 2003

Server Client Sockets

, 25 Apr 2003
Sample application Uses Server and client socket to establish exchange of data
#include <stdio.h>
#include <winsock.h>
#include <windows.h>

#define SERVER_SOCKET_ERROR 1
#define SOCKET_OK 0

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

void socketError(char*);

int WINAPI WinMain(	HINSTANCE hInst, HINSTANCE hPrevInstance, 
					LPSTR lpCmdLine, int nShow)
{
	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;

	client = accept(s, NULL, NULL);

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

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

	WSACleanup();

	return SOCKET_OK;
};

void socketError(char* str)
{
	MessageBox(NULL, str, "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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Emiliano
Web Developer
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Pro
Pro
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171020.1 | Last Updated 26 Apr 2003
Article Copyright 2003 by Emiliano
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid