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

C++ Socket library tutorial

Builtin connection retry and reconnect

Prev   |   Menu   |   Next

With version 1.9 of the sockets library, connection retry and reconnect on broken link for TcpSocket's were added. With this addition, the developer will be freed from most of the coding to take care of these scenarios. Also, overall performance should improve because socket objects will be preserved instead of deleted and recreated.

Connection retry

With a few method calls, behaviour on failed connections can now be controlled fully.

SetConnectTimeout( seconds ) is an old method that has been there for a while. If no connection has been established in the time specified, a connection retry or a call to OnConnectFailed will be generated. Default time is 5 seconds.

SetConnectionRetry( number ) controls how many connection retries will be made. A value of -1 means unlimited retries (use with caution!). Value "0" means that no connection retry should be made (default). A value greater than zero indicates the number of retries should be made.

OnConnectRetry() This callback method is called before a new connection attempt is made. The method can return false to abort the connection attempt and remove the socket object.

Reconnect on broken link

Established connections that for whatever reason breaks can be automatically reconnected.

SetReconnect( true / false ) When this flag is set "true", a broken connection will attempt to reconnect. The old socket file descriptor is closed, and a new one is created. Remember to set it "false" when you are about to normally terminate the connection.

OnReconnect() This callback is called when a connection has been reestablished. OnConnect() will not be called when the connection was a reconnect.

ResumeSocket2

ResumeSocket2 is totally without functionality, just an example of the new methods / callbacks.

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


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

	bool OnConnectRetry();
	void OnReconnect();

private:
	ResumeSocket2(const ResumeSocket2& s) : TcpSocket(s) {} // copy constructor
	ResumeSocket2& operator=(const ResumeSocket2& ) { return *this; } // assignment operator

};

Socket class implementation.

ResumeSocket2.cpp
#include "ResumeSocket2.h"


ResumeSocket2::ResumeSocket2(ISocketHandler& h)
:TcpSocket(h)
{
	// initial connection timeout setting and number of retries
	SetConnectTimeout(12);
	SetConnectionRetry(5);

	// Also reconnect broken link
	SetReconnect(true);
}


bool ResumeSocket2::OnConnectRetry()
{
	return true;
}


void ResumeSocket2::OnReconnect()
{
	// ...
	Send("Welcome back\r\n");
}

Prev   |   Menu   |   Next

Valid HTML 4.01!

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