Home  +  Forums  +  C++ and Sockets  +  C++ and SQL: MySQL, sqlite, ODBC  +  Miscellaneous Projects
Logo
~Sockets~
~New~
~Examples~
~Contact~

C++ Socket library tutorial

Building a custom SocketHandler

Prev   |   Menu   |   Next

This is a derived SocketHandler class, that is able to format output to sockets (using the tprintf() method), List() status about all Socket's in its socket list, Update() that information to all connected StatusSocket's, and finally Disconnect()'s StatusSocket's after 60 seconds connection time.

StatusHandler.h
#ifndef _STATUSHANDLER_H
#define _STATUSHANDLER_H

#include <SocketHandler.h>
#include <TcpSocket.h>


class StatusHandler : public SocketHandler
{
public:
	StatusHandler();

	void tprintf(TcpSocket *,char *format, ...);
	void List(TcpSocket *);
	void Update();
	void Disconnect();
};


#endif // _STATUSHANDLER_H

StatusHandler.cpp
#include <stdarg.h>
#include "StatusSocket.h"
#include "StatusHandler.h"


StatusHandler::StatusHandler()
:SocketHandler()
{
}


#define SIZE 5000
void StatusHandler::tprintf(TcpSocket *p,char *format, ...)
{
	va_list ap;
	size_t n;
	char tmp[SIZE];

	va_start(ap,format);
	n = vsnprintf(tmp,SIZE - 1,format,ap);
	va_end(ap);

	p -> SendBuf(tmp, strlen(tmp));
}


void StatusHandler::List(TcpSocket *sendto)
{
	tprintf(sendto, "Handler Socket List\n");
	for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++)
	{
		Socket *p = (*it).second;
		TcpSocket *p3 = dynamic_cast<TcpSocket *>(p);
		StatusSocket *p4 = dynamic_cast<StatusSocket *>(p);
		tprintf(sendto, " %s:%d",p -> GetRemoteAddress().c_str(),p -> GetRemotePort());
		tprintf(sendto, "  %s  ",p -> Ready() ? "Ready" : "NOT_Ready");
		if (p4)
		{
			tprintf(sendto, "StatusSocket");
		}
		tprintf(sendto, "\n");
		tprintf(sendto, "  Uptime:  %d days %02d:%02d:%02d\n",
			p -> Uptime() / 86400,
			(p -> Uptime() / 3600) % 24,
			(p -> Uptime() / 60) % 60,
			p -> Uptime() % 60);
		if (p3)
		{
			tprintf(sendto, "    Bytes Read: %9lu\n",p3 -> GetBytesReceived());
			tprintf(sendto, "    Bytes Sent: %9lu\n",p3 -> GetBytesSent());
		}
	}
	tprintf(sendto, "\n");
}


void StatusHandler::Update()
{
	for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++)
	{
		Socket *p0 = (*it).second;
		StatusSocket *p = dynamic_cast<StatusSocket *>(p0);
		if (p)
		{
			List(p);
		}
	}
}


void StatusHandler::Disconnect()
{
	for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++)
	{
		Socket *p0 = (*it).second;
		TcpSocket *p = dynamic_cast<TcpSocket *>(p0);
		if (p && p -> Uptime() > 60 )
		{
			tprintf(p, "Goodbye\n");
			p -> SetCloseAndDelete();
		}
	}
}



Prev   |   Menu   |   Next

Valid HTML 4.01!

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