Click here to Skip to main content
15,886,199 members
Articles / Desktop Programming / MFC

Writing Scalable Server Applications using IOCP

Rate me:
Please Sign up or sign in to vote.
4.15/5 (29 votes)
5 Feb 2001 453.4K   9.1K   155  
An article about using I/O Completion Ports and Winsock to write robust and scalable Windows server applications
// Written by Oz Ben Eliezer
// o_be@hotmail.com
// September, 2000

#define _WIN32_WINNT 0x0500

#include <windows.h>

#include "callback.h"
#include "client_0.h"
#include "general.h"

#define NUM_CLIENTS		1000		// You probably would make this a
									// configurable value
#define TCP_PORT		10
#define CHECK_CYCLE		10000		// Check for static connections every...

SOCKET listener;
CClient_0 *pClients[NUM_CLIENTS];
HANDLE dieEvent;
char *temptemp;
int CClient::nID;

int main()
{
	int i;

	// Initialize
	dieEvent = CreateEvent(0, true, false, 0);

	CClient::nID = 0;

	WSADATA wd = {0};
	err(0 != WSAStartup(MAKEWORD(2, 0), &wd), "\nWSAStartup(..) failed.");
	SOCKADDR_IN addr;
	err(INVALID_SOCKET == (listener = socket(AF_INET, SOCK_STREAM, 0)),
		"\nCan't create listener socket.");
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = INADDR_ANY;
	addr.sin_port = htons((short)TCP_PORT);

	err(0 != bind(listener, (SOCKADDR *)&addr, sizeof(addr)),
		"\nbind(..) failed.");
	err(0 != listen(listener, 200),
		"\nlisten(..) failed.");

	err(0 == BindIoCompletionCallback((HANDLE)listener, DoneIO, 0),
		"\nBindIoCompletionCallback failed.");


	for (i = 0; i < NUM_CLIENTS; i++)
	{
		pClients[i] = new CClient_0();
		pClients[i]->Init();
	}


	while (WAIT_TIMEOUT == WaitForSingleObject(dieEvent, CHECK_CYCLE))
	{
		for (i = 0; i < NUM_CLIENTS; i++)
			pClients[i]->Maintenance();
	}

	// Done
	for (i = 0; i < NUM_CLIENTS; i++)
	{
		pClients[i]->Close();
		delete pClients[i];
	}

	closesocket(listener);

	CloseHandle(dieEvent);

	return 0;
}

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
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions