C++ Socket library tutorial
|
|
New in 2.0: timer events
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.
MyEventSocket.h
#include <TcpSocket.h>
#include <IEventOwner.h>
#include "MyEventHandler.h"
class MyEventSocket : public TcpSocket,public IEventOwner
{
public:
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.
event.cpp
#include <ListenSocket.h>
#include "MyEventHandler.h"
#include "MyEventSocket.h"
int main()
{
MyEventHandler h;
ListenSocket<MyEventSocket> l(h);
l.Bind(40041);
h.Add(&l);
h.EventLoop();
}
|
|
Also available
MyEventHandler.h
and
MyEventHandler.cpp.
|