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

Introduction

Prev   |   Menu   |   Next

Welcome to the tutorial of the C++ socket library. I'm a big fan of learn by example and not by reference manual, so expect to see a lot of code snippets.

The C++ socket library is an event-driven client/server networking framework, nothing more and nothing less. External components / methods / libraries include STL (www.sgi.com/tech/stl), openssl (www.openssl.org), and pthreads (linux). Oh, and one other thing. It's a single-threaded design, but socket classes have the ability to run by themselves in their own thread.

Apart from the few utility classes in the library, two types of classes must be described more in detail. The Socket class, which all different IP and higher level protocols are derived from; and the SocketHandler class which acts as the controller / event handler / dispatcher.

A program (client or server) consists of one SocketHandler class, that can handle one or more Socket classes. The SocketHandler keeps track of the socket list, and calls select() to get the next event (read / write / exception). It also tracks the progress of outgoing connections.

When the SocketHandler receives an event for a socket, that event is reported directly to the Socket class using a callback method. The most basic callback methods are OnRead(), OnWrite(), OnConnect(), OnAccept(). Here are the rest, to complete the list: OnException(), OnDelete(), OnLine(), OnSSLInitDone(), OnRawData(), OnDetached().

The C++ socket library consists of different Socket class specializations such as TcpSocket, UdpSocket, SSLSocket. To add functionality, to actually make a socket read and write stuff, a new class must be created that inherits one of the Socket classes. The following pages will show examples how to create new Socket classes, and also how to use them in a client / server program.

Most of the time, the SocketHandler class by itself can handle a lot of the stuff to make a client / server program tick. But when sockets have to interact, it is most pratical to create a new SocketHandler derived class also. The third example will show this.

Prev   |   Menu   |   Next

Valid HTML 4.01!

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