Boost.Asio - 4. TCP Socket Programming - 2020
The Boost.Asio provides many I/O objects to develop network applications. Though Boost.Asio is a library that can process any kind of data asynchronously, it is mainly being used for network programming.
As we can see from the subsequent samples, it provides developers with a consistent asynchronous I/O model using a modern C++ approach.
The materials used in this section are based on the daytime protocol and mostly borrowed from Introduction to Sockets.
"The Daytime Protocol is a service in the Internet Protocol Suite, defined in 1983 in RFC 867. It is intended for testing and measurement purposes in computer networks. A host may connect to a server that supports the Daytime Protocol on either Transmission Control Protocol (TCP) or User Datagram Protocol (UDP) port 13".
From http://en.wikipedia.org/wiki/Daytime_Protocol:
On UNIX-like operating systems a daytime server is usually built into the inetd (or xinetd) daemon. The service is usually not enabled by default. It may be enabled by adding the following lines to the file /etc/inetd.conf and telling inetd to reload its configuration:
daytime stream tcp nowait root internal daytime dgram udp wait root internal
An example output may be:
Tuesday, February 22, 1982 18:45:59-PST
This sample code shows how to use asio to implement a server application with TCP.
#include <ctime> #include <iostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; std::string make_daytime_string() { std::time_t now = std::time(0); return std::ctime(&now;); } int main() { try { // Any program that uses asio need to have at least one io_service object boost::asio::io_service io_service; // acceptor object needs to be created to listen for new connections tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13)); for (;;) { // creates a socket tcp::socket socket(io_service); // wait and listen acceptor.accept(socket); // prepare message to send back to client std::string message = make_daytime_string(); boost::system::error_code ignored_error; // writing the message for current time boost::asio::write(socket, boost::asio::buffer(message), ignored_error); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
Here is the code: server.cpp.
First, we defined the function make_daytime_string() to create the string to be sent back to the client.
Any program that uses asio need to have at least one io_service object:
boost::asio::io_service io_service;
A ip::tcp::acceptor object needs to be created to listen for new connections. It is initialised to listen on TCP port 13, for IP version 4:
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));
This is an iterative server that it handles one connection at a time. We creates a socket that represents the connection to the client, and then waits for a connection:
tcp::socket socket(io_service); acceptor.accept(socket);
When a client is accessing our service. This server should determine the current time and transfer this information to the client:
std::string message = make_daytime_string(); boost::system::error_code ignored_error; boost::asio::write(socket, boost::asio::buffer(message), ignored_error);
Let's run the server:
$ ./server
#include <iostream> #include <boost/array.hpp> #include <boost/asio.hpp> using boost::asio::ip::tcp; int main(int argc, char* argv[]) { try { // the user should specify the server - the 2nd argument if (argc != 2) { std::cerr << "Usage: client" << std::endl; return 1; } // Any program that uses asio need to have at least one io_service object boost::asio::io_service io_service; // Convert the server name that was specified as a parameter to the application, to a TCP endpoint. // To do this, we use an ip::tcp::resolver object. tcp::resolver resolver(io_service); // A resolver takes a query object and turns it into a list of endpoints. // We construct a query using the name of the server, specified in argv[1], // and the name of the service, in this case "daytime". tcp::resolver::query query(argv[1], "daytime"); // The list of endpoints is returned using an iterator of type ip::tcp::resolver::iterator. // A default constructed ip::tcp::resolver::iterator object can be used as an end iterator. tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); // Now we create and connect the socket. // The list of endpoints obtained above may contain both IPv4 and IPv6 endpoints, // so we need to try each of them until we find one that works. // This keeps the client program independent of a specific IP version. // The boost::asio::connect() function does this for us automatically. tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); // The connection is open. All we need to do now is read the response from the daytime service. for (;;) { // We use a boost::array to hold the received data. boost::array buf; boost::system::error_code error; // The boost::asio::buffer() function automatically determines // the size of the array to help prevent buffer overruns. size_t len = socket.read_some(boost::asio::buffer(buf), error); // When the server closes the connection, // the ip::tcp::socket::read_some() function will exit with the boost::asio::error::eof error, // which is how we know to exit the loop. if (error == boost::asio::error::eof) break; // Connection closed cleanly by peer. else if (error) throw boost::system::system_error(error); // Some other error. std::cout.write(buf.data(), len); } } // handle any exceptions that may have been thrown. catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
Here is the code: client.cpp.
If the client request connection, it gets the current time:
$ ./client 127.0.0.1 Sat Feb 15 12:27:13 2014
#include <ctime> #include <iostream> #include <string> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/asio.hpp> using boost::asio::ip::tcp; std::string make_daytime_string() { std:: time_t now = std::time(0); return std::ctime(&now;); } class tcp_connection // Using shared_ptr and enable_shared_from_this // because we want to keep the tcp_connection object alive // as long as there is an operation that refers to it. : public boost::enable_shared_from_this<tcp_connection> { public: typedef boost::shared_ptr<tcp_connection> pointer; static pointer create(boost::asio::io_service& io_service) { return pointer(new tcp_connection(io_service)); } tcp::socket& socket() { return socket_; } // Call boost::asio::async_write() to serve the data to the client. // We are using boost::asio::async_write(), // rather than ip::tcp::socket::async_write_some(), // to ensure that the entire block of data is sent. void start() { // The data to be sent is stored in the class member m_message // as we need to keep the data valid // until the asynchronous operation is complete. m_message = make_daytime_string(); // When initiating the asynchronous operation, // and if using boost::bind(), // we must specify only the arguments // that match the handler's parameter list. // In this code, both of the argument placeholders // (boost::asio::placeholders::error // and boost::asio::placeholders::bytes_transferred) // could potentially have been removed, // since they are not being used in handle_write(). boost::asio::async_write(socket_, boost::asio::buffer(m_message), boost::bind(&tcp;_connection::handle_write, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } private: tcp_connection(boost::asio::io_service& io_service) : socket_(io_service) { } // handle_write() is responsible for any further actions // for this client connection. void handle_write(const boost::system::error_code& /*error*/, size_t /*bytes_transferred*/) { } tcp::socket socket_; std::string m_message; }; class tcp_server { public: // Constructor: initialises an acceptor to listen on TCP port 13. tcp_server(boost::asio::io_service& io_service) : acceptor_(io_service, tcp::endpoint(tcp::v4(), 13)) { // start_accept() creates a socket and // initiates an asynchronous accept operation // to wait for a new connection. start_accept(); } private: void start_accept() { // creates a socket tcp_connection::pointer new_connection = tcp_connection::create(acceptor_.get_io_service()); // initiates an asynchronous accept operation // to wait for a new connection. acceptor_.async_accept(new_connection->socket(), boost::bind(&tcp;_server::handle_accept, this, new_connection, boost::asio::placeholders::error)); } // handle_accept() is called when the asynchronous accept operation // initiated by start_accept() finishes. It services the client request void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error) { if (!error) { new_connection->start(); } // Call start_accept() to initiate the next accept operation. start_accept(); } tcp::acceptor acceptor_; }; int main() { try { // We need to create a server object to accept incoming client connections. boost::asio::io_service io_service; // The io_service object provides I/O services, such as sockets, // that the server object will use. tcp_server server(io_service); // Run the io_service object to perform asynchronous operations. io_service.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
Here is the code: async_server.cpp.
Let's run the server and then client:
$ ./async_server $ ./client 127.0.0.1 Sat Feb 15 12:50:53 2014
References used in this chapter:
- http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/tutorial.html.
- http://en.highscore.de/cpp/boost/asio.html.
C++ Tutorials
C++ HomeAlgorithms & Data Structures in C++ ...
Application (UI) - using Windows Forms (Visual Studio 2013/2012)
auto_ptr
Binary Tree Example Code
Blackjack with Qt
Boost - shared_ptr, weak_ptr, mpl, lambda, etc.
Boost.Asio (Socket Programming - Asynchronous TCP/IP)...
Classes and Structs
Constructor
C++11(C++0x): rvalue references, move constructor, and lambda, etc.
C++ API Testing
C++ Keywords - const, volatile, etc.
Debugging Crash & Memory Leak
Design Patterns in C++ ...
Dynamic Cast Operator
Eclipse CDT / JNI (Java Native Interface) / MinGW
Embedded Systems Programming I - Introduction
Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora
Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain
Exceptions
Friend Functions and Friend Classes
fstream: input & output
Function Overloading
Functors (Function Objects) I - Introduction
Functors (Function Objects) II - Converting function to functor
Functors (Function Objects) - General
Git and GitHub Express...
GTest (Google Unit Test) with Visual Studio 2012
Inheritance & Virtual Inheritance (multiple inheritance)
Libraries - Static, Shared (Dynamic)
Linked List Basics
Linked List Examples
make & CMake
make (gnu)
Memory Allocation
Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.
Multi-Threaded Programming II - Native Thread for Win32 (A)
Multi-Threaded Programming II - Native Thread for Win32 (B)
Multi-Threaded Programming II - Native Thread for Win32 (C)
Multi-Threaded Programming II - C++ Thread for Win32
Multi-Threaded Programming III - C/C++ Class Thread for Pthreads
MultiThreading/Parallel Programming - IPC
Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)
Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)
Multithread Debugging
Object Returning
Object Slicing and Virtual Table
OpenCV with C++
Operator Overloading I
Operator Overloading II - self assignment
Pass by Value vs. Pass by Reference
Pointers
Pointers II - void pointers & arrays
Pointers III - pointer to function & multi-dimensional arrays
Preprocessor - Macro
Private Inheritance
Python & C++ with SIP
(Pseudo)-random numbers in C++
References for Built-in Types
Socket - Server & Client
Socket - Server & Client 2
Socket - Server & Client 3
Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)
Stack Unwinding
Standard Template Library (STL) I - Vector & List
Standard Template Library (STL) II - Maps
Standard Template Library (STL) II - unordered_map
Standard Template Library (STL) II - Sets
Standard Template Library (STL) III - Iterators
Standard Template Library (STL) IV - Algorithms
Standard Template Library (STL) V - Function Objects
Static Variables and Static Class Members
String
String II - sstream etc.
Taste of Assembly
Templates
Template Specialization
Template Specialization - Traits
Template Implementation & Compiler (.h or .cpp?)
The this Pointer
Type Cast Operators
Upcasting and Downcasting
Virtual Destructor & boost::shared_ptr
Virtual Functions
Programming Questions and Solutions ↓
Strings and Arrays
Linked List
Recursion
Bit Manipulation
Small Programs (string, memory functions etc.)
Math & Probability
Multithreading
140 Questions by Google
Qt 5 EXPRESS...
Win32 DLL ...
Articles On C++
What's new in C++11...
C++11 Threads EXPRESS...
Go Tutorial
OpenCV...
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization