Home  +  Forums  +  C++ and Sockets  +  C++ and SQL: MySQL, sqlite, ODBC  +  Miscellaneous Projects

C++ Socket library tutorial

New in 2.0: timer events

Prev   |   Menu   |   Next

Included in version 2.0 of the C++ sockets library is a specialized EventHandler class that extends the functionality of the standard SocketHandler.

Objects that want an event callback some time in the future can register themselves with the event handler, and will later on receive the event callback on the method OnEvent.

Classes that want to implement the event callback method must inherit from the interface class IEventOwner.

Socket implementing an event callback method.

#include <TcpSocket.h>
#include <IEventOwner.h>
#include "MyEventHandler.h"

class MyEventSocket : public TcpSocket,public IEventOwner
	MyEventSocket(ISocketHandler& h) : TcpSocket(h), IEventOwner( static_cast<MyEventHandler&>(h) )
		SetLineProtocol(); // we want to receive line callbacks

	void OnLine(const std::string& line)
		if (line == "event")
			// schedule an event 2 seconds ahead in time
			int id = static_cast<MyEventHandler&>(Handler()).AddEvent(this, 2, 0);
			Send("Scheduled event id " + Utility::l2string(id) + "\n");

	void OnEvent(int id)
		Send("Event id " + Utility::l2string(id) + "\n");

Main program using above Socket.

#include <ListenSocket.h>
#include "MyEventHandler.h"
#include "MyEventSocket.h"

int main()
	MyEventHandler h;
	ListenSocket<MyEventSocket> l(h);

Also available MyEventHandler.h and MyEventHandler.cpp.

Prev   |   Menu   |   Next

Valid HTML 4.01!

Page, code, and content Copyright (C) 2021 by Anders Hedström