Click here to Skip to main content
13,143,985 members (33,103 online)
Click here to Skip to main content
Add your own
alternative version

Stats

1.5M views
82.1K downloads
639 bookmarked
Posted 22 Jun 2002

Multi-threaded Client/Server Socket Class

, 10 Feb 2009
Rate this:
Please Sign up or sign in to vote.
A multi-threaded based Client/Server Socket Communication class

Screenshots

Note: The demo can be started in Client or Server mode, executed with "/C" (or "/CLIENT") or "/S" (or "/SERVER", which is the default).

Server Socket App - Screenshot

Client Socket App - Screenshot

Introduction

This article is about a client/server multi-threaded socket class. The thread is optional since the developer/designer is still responsible for deciding if he/she needs it. There are other Socket classes here and other places over the Internet, but none of them can provide feedback (event detection) to your application like this one does. It provides you with the following events detection: connection established, connection dropped, connection failed and data reception (including 0 byte packet).

Description

This article presents a new socket class which supports both TCP and UDP communication. It provides some advantages compared to other classes that you may find here or on some other Socket Programming articles. First of all, this class doesn't have any limitation like the need to provide a window handle to be used. This limitation is bad if all you want is a simple console application. So, this library doesn't have such a limitation. It also provides threading support automatically for you, which handles the socket connection and disconnection to a peer. It also features some options not yet found in any socket classes that I have seen so far. It supports both client and server sockets. A server socket can be referred as to a socket that can accept many connections. A client socket is a socket that is connected to a server socket. You may still use this class to communicate between two applications without establishing a connection. In the latter case, you will want to create two UDP server sockets (one for each application). This class also helps reduce coding needed to create chat-like applications and IPC (Inter-Process Communication) between two or more applications (processes). Reliable communication between two peers is also supported with TCP/IP with error handling. You may want to use the smart addressing operation to control the destination of the data being transmitted (UDP only). TCP operation of this class deals only with communication between two peers.

Now for those not familiar with IP Socket, the following section will give some details on how it works. This is also the goal with this article: to explain the basic functionality behind socket objects.

TCP/IP Stack

The TCP/IP stack is shorter than the OSI one:

TCP is a connection-oriented protocol, while UDP (User Datagram Protocol) is a connectionless protocol.

IP Datagrams

The IP layer provides a connectionless and unreliable delivery system. It considers each datagram independently of the others. Any association between datagrams must be supplied by the higher layers. The IP layer supplies a checksum that includes its own header. The header includes the source and destination addresses. The IP layer handles routing through the Internet. It is also responsible for breaking up large datagrams into smaller ones for transmission and reassembling them at the other end.

UDP

UDP is also connectionless and unreliable. What it adds to IP is a checksum for the contents of the datagram and port numbers. These are used to give a client/server model: see later.

TCP

TCP supplies logic to give a reliable connection-oriented protocol above IP. It provides a virtual circuit that two processes can use to communicate.

Internet Addresses

In order to use a service, you must be able to find it. The Internet uses an address scheme for machines so that they can be located. The address is a 32-bit integer which gives the IP address. This encodes a network ID and more addressing. The network ID falls into various classes according to the size of the network address.

Network Address

Class A uses 8 bits for the network address with 24 bits left over for other addressing. Class B uses 16-bit network addressing; class C uses 24-bit network addressing and class D uses all 32.

Subnet Address

Internally, the Unix network is divided into subnetworks. Building 11 is currently on one subnetwork and uses 10-bit addressing, allowing 1024 different hosts.

Host Address

8 bits are finally used for host addresses within our subnet. This places a limit of 256 machines that can be on the subnet.

Total Address

The 32-bit address is usually written as 4 integers separated by dots.

Port Addresses

A service exists on a host and is identified by its port. This is a 16-bit number. To send a message to a server, you send it to the port for that service of the host that it is running on. This is not location transparency! Some of these ports are "well known." For example:

tcpmux1TCP
echo7UDP
echo7TCP
systat11TCP
netstat15TCP
ftp-data20TCP File Transfer Protocol (data)
ftp21TCP File Transfer Protocol
smtp25TCP Simple Mail Transfer Protocol
time37TCP Time Server
time37UDP Time Server
name42UDP Name Server
whois43TCP nicname
domain53UDP
domain53TCP
tftp69UDP
rje77TCP
finger79TCP
link87TCP ttylink
supdup95TCP
hostname101TCP hostname
pop-2109TCP Post Office Protocol
uucp-path117TCP
nntp119TCP Network News Transfer Protocol
ntp123TCP Network Time Protocol

Ports in the region 1-255 are reserved by TCP/IP. The system may reserve more. User processes may have their own ports above 1023. The function getservbyname can be used to find the port for a service that is registered.

Sockets

A socket is a data structure maintained by the system to handle network connections. A socket is created using the call socket. It returns an integer that is like a file descriptor. In fact, under Windows, this handle can be used with the ReadFile and WriteFile functions.

#include <sys/types.h>
#include <sys/socket.h>
int socket(int family, int type, int protocol);

Here, family will be AF_INET for IP communications, protocol will be zero and type will depend on whether TCP or UDP is used. Two processes wishing to communicate over a network create a socket each. These are similar to two ends of a pipe, but the actual pipe does not yet exist.

Connection Oriented (TCP)

One process (server) makes its socket known to the system using bind. This will allow other sockets to find it. It then "listens" on this socket to "accept" any incoming messages. The other process (client) establishes a network connection to it and then the two exchange messages. As many messages as needed may be sent along this channel, in either direction.

Server

  • Create endpoint (socket())
  • Bind address (bind())
  • Specify queue (listen())
  • Wait for connection (accept())
  • Transfer data (read()/write())

Client

  • Create endpoint (socket())
  • Connect to server (connect())
  • Transfer data (read()/write())

Connectionless (UDP)

In a connectionless protocol, both sockets have to make their existence known to the system using bind. This is because each message is treated separately, so the client has to find the server each time it sends a message and vice versa. When bind is called, it binds to a new port. It cannot bind to one already in use. If you specify the port as zero, the system gives you a currently unused port. Because of this extra task on each message send, the processes do not use read/write, but recvfrom/sendto. These functions take as parameters the socket to write to and the address of the service on the remote machine.

Server

  • Create endpoint (socket())
  • Bind address (bind())
  • Transfer data (sendto()/recvfrom())

Client

  • Create endpoint (socket())
  • Bind address (bind()) (optional if connect is called)
  • Connect to server (connect())
  • Transfer data (sendto()/recvfrom())

Version History

////////////////////////////////////////////////////////////////////////
//    File:        SocketComm.cpp
//    Version:     1.4
//
//  1.0 - Initial release.
//  1.1 - Added support for Smart Addressing mode
//  1.2 - Fixed various issues with address list (in UDP mode)
//  1.3 - Fix bug when sending message to broadcast address
//  1.4 - Add UDP multicast support
////////////////////////////////////////////////////////////////////////

How to Use

This class can be used to create a TCP or UDP socket. Its use is very simple. First of all, the CSocketComm class is not completed by itself for server operation. This class must be derived. Fortunately, only two functions need to be created, OnDataReceived and OnEvent. The default functions don't do anything. Now to create and start a server socket, do the following:

// To use TCP socket
// no smart addressing - we use connection oriented
m_SocketObject.SetSmartAddressing( false ); 
m_SocketObject.CreateSocket( m_strPort, AF_INET, SOCK_STREAM,0); // TCP

// To use UDP socket
m_SocketObject.SetSmartAddressing( true );
m_SocketObject.CreateSocket( m_strPort, 
   AF_INET, SOCK_DGRAM, SO_BROADCAST); // UDP

// Now you may start the server/client thread to do the work for you...
m_SocketObject.WatchComm();

To create and start a client socket, do the following:

// To use TCP socket
m_SocketObject.ConnectTo( strServer, m_strPort, AF_INET, SOCK_STREAM); // TCP

// To use UDP socket
m_SocketObject.ConnectTo( strServer, m_strPort, AF_INET, SOCK_DGRAM); // UDP

// Now you may start the server/client thread to do the work for you...
m_SocketObject.WatchComm();

References

History

  • Aug 31, 2002: Updated source code
  • Mar 01, 2004: Updated source code
  • Apr 02, 2004: Fixed bug when sending message to broadcast address
  • Feb 07, 2009: Updated source code (Visual Studio 2005 project)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ernest Laurentin
Software Developer (Senior)
United States United States
Ernest is a multi-discipline software engineer.
Skilled at software design and development for all Windows platforms.
-
MCSD (C#, .NET)
Interests: User Interface, GDI/GDI+, Scripting, Android, iOS, Windows Mobile.
Programming Skills: C/C++, C#, Java (Android), VB and ASP.NET.

I hope you will enjoy my contributions.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questiongood Pin
poorfool922-Jan-16 17:34
memberpoorfool922-Jan-16 17:34 
QuestionHow to make client socket wait for data from server? Pin
ntdoan.bksprecision3-Sep-14 18:34
memberntdoan.bksprecision3-Sep-14 18:34 
AnswerRe: How to make client socket wait for data from server? Pin
Ernest Laurentin3-Sep-14 19:32
memberErnest Laurentin3-Sep-14 19:32 
GeneralRe: How to make client socket wait for data from server? Pin
ntdoan.bksprecision14-Sep-14 1:24
memberntdoan.bksprecision14-Sep-14 1:24 
Questionissue about use address : 127.0.0.1 Pin
lion_11727-Aug-14 17:16
memberlion_11727-Aug-14 17:16 
AnswerRe: issue about use address : 127.0.0.1 Pin
Ernest Laurentin27-Aug-14 18:44
memberErnest Laurentin27-Aug-14 18:44 
GeneralRe: issue about use address : 127.0.0.1 Pin
lion_11727-Aug-14 20:10
memberlion_11727-Aug-14 20:10 
GeneralRe: issue about use address : 127.0.0.1 Pin
Ernest Laurentin3-Sep-14 19:29
memberErnest Laurentin3-Sep-14 19:29 
QuestionProblem with the Thread-Pool Pin
McKool24-Jun-13 2:18
memberMcKool24-Jun-13 2:18 
QuestionThere is a serious design problem? Pin
fishjam14-Apr-13 17:53
memberfishjam14-Apr-13 17:53 
AnswerRe: There is a serious design problem? Pin
Ernest Laurentin14-Apr-13 18:11
memberErnest Laurentin14-Apr-13 18:11 
GeneralMy vote of 5 Pin
Liu_yh1-Mar-13 14:27
memberLiu_yh1-Mar-13 14:27 
QuestionNeed to add an edit box Pin
Member 985352024-Feb-13 5:46
memberMember 985352024-Feb-13 5:46 
Questionclient config Pin
Member 86380346-Nov-12 2:40
memberMember 86380346-Nov-12 2:40 
AnswerRe: client config Pin
Liu_yh1-Mar-13 14:28
memberLiu_yh1-Mar-13 14:28 
QuestionWhy does it hang the client if using 64 bit x64 platform in Visual Studio if Server is running? Pin
singan1031-Jul-12 10:15
membersingan1031-Jul-12 10:15 
QuestionHow do I get about Client IP in Server application Pin
cliff_liu19-Jul-12 19:50
membercliff_liu19-Jul-12 19:50 
AnswerRe: How do I get about Client IP in Server application Pin
jacksp15-Jan-13 21:48
memberjacksp15-Jan-13 21:48 
GeneralRe: How do I get about Client IP in Server application Pin
jacksp17-Jan-13 18:47
memberjacksp17-Jan-13 18:47 
GeneralMy vote of 4 Pin
almerak18-Jul-12 6:00
memberalmerak18-Jul-12 6:00 
QuestionPlease upload client file Pin
lehoang_khang17-May-12 20:35
memberlehoang_khang17-May-12 20:35 
AnswerRe: Please upload client file Pin
Member 910746611-Jun-12 19:26
memberMember 910746611-Jun-12 19:26 
GeneralMy vote of 5 Pin
johneybaraba20-Apr-12 5:41
memberjohneybaraba20-Apr-12 5:41 
QuestionClient disconnecting during Server Write causes crash in UDP mode Pin
xumepoc20-Dec-11 4:57
memberxumepoc20-Dec-11 4:57 
QuestionWhy I can only get 30 percent response from sever? Pin
Night Ant4-Dec-11 21:38
memberNight Ant4-Dec-11 21:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 10 Feb 2009
Article Copyright 2002 by Ernest Laurentin
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid