Multi-threaded Client/Server Socket Class
2015-09-03 17:01
309 查看
Multi-threaded Client/Server Socket Class
ErnestLaurentin, 10 Feb 2009
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).
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 noneof 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 limitationlike 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 ownheader. 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 IDfalls 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 "wellknown." For example:
tcpmux | 1 | TCP |
echo | 7 | UDP |
echo | 7 | TCP |
systat | 11 | TCP |
netstat | 15 | TCP |
ftp-data | 20 | TCP File Transfer Protocol (data) |
ftp | 21 | TCP File Transfer Protocol |
smtp | 25 | TCP Simple Mail Transfer Protocol |
time | 37 | TCP Time Server |
time | 37 | UDP Time Server |
name | 42 | UDP Name Server |
whois | 43 | TCP nicname |
domain | 53 | UDP |
domain | 53 | TCP |
tftp | 69 | UDP |
rje | 77 | TCP |
finger | 79 | TCP |
link | 87 | TCP ttylink |
supdup | 95 | TCP |
hostname | 101 | TCP hostname |
pop-2 | 109 | TCP Post Office Protocol |
uucp-path | 117 | TCP |
nntp | 119 | TCP Network News Transfer Protocol |
ntp | 123 | TCP Network Time Protocol |
getservbynamecan
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 callsocket.
It returns an integer that is like a file descriptor. In fact, under Windows, this handle can be used with the
ReadFileand
WriteFilefunctions.
#include <sys/types.h> #include <sys/socket.h> int socket(int family, int type, int protocol);
Here,
familywill be
AF_INETfor
IP communications,
protocolwill be zero and
typewill
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 usingbind. 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 usingbind. 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
bindis
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
connectis
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 CSocketCommclass
is not completed by itself for server operation. This class must be derived. Fortunately, only two functions need to be created,
OnDataReceivedand
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
SocketLibrary Functions
Windows Sockets
History
Aug 31, 2002: Updated source codeMar 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 TheCode Project Open License (CPOL)
附件下载:http://download.csdn.net/detail/jinvmen/9076203。
声明:附件来源于互联网,仅供参考学习,如果用于商业请联系作者Ernest
Laurentin。
相关文章推荐
- 新发现:AirDroid(用Web端控制自己的手机发信息)
- 1023. 组个最小数
- string.h c源码实现
- 转载:关于SpannableString的一些用法
- Linux系统中valgrind检查内存泄露
- linux内核之内核与ring3的通信
- 华为Java面试题目总结
- at org.apache.jsp.admin.index_jsp._jspInit(index_jsp.java:29)的解决方法
- JAVA面试(未完)
- MySql存储过程例子1
- JohnsonTroter 排列生成算法
- 数据库锁机制
- MB、MiB、GB、GiB的定义
- PAT 1081. Rational Sum (20)
- lintcode-硬币排成一条线
- 迭代器模式(一):销售管理系统中数据的遍历
- web_reg_find和web_find的区别
- spark源码剖析之----Partitioner
- shell里面的test用法
- HDU 4568【最短路+状压DP】