Boost library consists of asio which is a free, cross-platform C++ library for network and low-level I/O programming that provides a consistent asynchronous model using a modern C++ approach. This article will help to develop a client-server synchronous chatting application using boost::asio. We are explicitly mentioning "synchronous" because in the synchronous model one of our client or server has to wait for another.
Server-Side Application: Below are the various steps to create the Server Side application:
- Importing boost/asio.hpp (Version: 220.127.116.11)
- Creating object of io_service (for server) which is mandatory for using boost::asio.
- Creating object of acceptor, passing io_service object and endpoint of connection i.e. IPv4 and port number 9999 (IPv6 protocol is also supported in boost::asio, also note that port 0 - 1233 are reserved).
- Creating tcp::socket object for our server.
- Invoking accept method of acceptor object to establish connection.
- read_until() method fetches message from the buffer which stores data during communication. Here we are using "\n" as out delimiter, which means we shall keep reading data from the buffer until we encounter "\n" and store it.
// Create buffer for storing
boost::asio::read_until(socket, buf, "\n");
string data = boost::asio::buffer_cast(buf.data());
- write() method writes data to the buffer taking socket object and message as parameter.
boost::asio::buffer(message + "\n"));
Client-Side Application: Below are the various steps to create the Client Side application:
- Importing boost/asio.hpp.
- Creating object of io_service for client.
- Creating tcp::socket object for client.
- Invoking connect method of socket object to initiate connection with server using localhost (IP 127.0.0.1) and connecting to same port 9999.
- read_until() and write() will remain same for our client application as well, as the Server side.
Below is the implementation of the above approach: Program: