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

C++ Socket library tutorial

Creating a socket that echoes input to screen

Prev   |   Menu   |   Next

This Socket class only has one method (besides the constructor). OnRead() is called by the SocketHandler when data is available in the TcpSocket input buffer. In this implementation, OnRead() will read a block of data from the input buffer and print it to the console using printf().

DisplaySocket.h
#include <TcpSocket.h>
#include <ISocketHandler.h>

class DisplaySocket : public TcpSocket
{
public:
	DisplaySocket(ISocketHandler& );

	void OnRead();
};

DisplaySocket.cpp
#include "DisplaySocket.h"

// the constant TCP_BUFSIZE_READ is the maximum size of the standard input
// buffer of TcpSocket
#define RSIZE TCP_BUFSIZE_READ

DisplaySocket::DisplaySocket(ISocketHandler& h) : TcpSocket(h)
{
}

void DisplaySocket::OnRead()
{
	// OnRead of TcpSocket actually reads the data from the socket
	// and moves it to the input buffer (ibuf)
	TcpSocket::OnRead();
	// get number of bytes in input buffer
	size_t n = ibuf.GetLength();
	if (n > 0)
	{
		char tmp[RSIZE]; // <--- tmp's here
		ibuf.Read(tmp,n);
		printf("Read %d bytes:\n",n);
		for (size_t i = 0; i < n; i++)
		{
			printf("%c",isprint(tmp[i]) ? tmp[i] : '.');
		}
		printf("\n");
	}
}

Prev   |   Menu   |   Next

Valid HTML 4.01!

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