Writing networking code that is portable is easy to maintain has been an issue since long. C++ took a step to resolve this issue by introducing boost.asio. It is a cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach. Here's a list of what it offers:
# Cross platform networking code (code would work on Windows, Linux, etc.)
# IPv4 and IPv6 support
# Asynchronous event support
# Timer support
# iostream compatibility
Syntax:
boost::asio::
Header File:
#include <boost/asio.hpp>
Sample Code:
-> Let's suppose we want our server to receive a message from client and then respond back. For that, we need two functions for read and write. For that let's break things down a little bit. Here, we are using tcp socket for communication. read_until and write functions from boost::asio has been used to perform the desired function. boost::asio::buffer creates a buffer of the data that is being communicated.
int main() {
boost::asio::io_service io_service;
//listen for new connection
tcp::acceptor acceptor_(io_service, tcp::endpoint(tcp::v4(), 1234 ));
//socket creation
tcp::socket socket_(io_service);
//waiting for connection
acceptor_.accept(socket_);
//read operation
string message = read_(socket_);
cout << message << endl;
//write operation
send_(socket_, "Hello From Server!");
cout << "Servent sent Hello message to Client!" << endl;
return 0;
}
-> Now we need the other end for our communication as well, i.e., a client that requests server. The basic structure is the same as we did for server.
int main() {
boost::asio::io_service io_service;
//socket creation
tcp::socket socket(io_service);
//connection
socket.connect( tcp::endpoint( boost::asio::ip::address::from_string("127.0.0.1"), 1234 ));
// request/message from client
const string msg = "Hello from Client!\n";
boost::system::error_code error;
boost::asio::write( socket, boost::asio::buffer(msg), error );
if( !error ) {
cout << "Client sent hello message!" << endl;
}
else {
cout << "send failed: " << error.message() << endl;
}
// getting response from server
boost::asio::streambuf receive_buffer;
boost::asio::read(socket, receive_buffer, boost::asio::transfer_all(), error);
if( error && error != boost::asio::error::eof ) {
cout << "receive failed: " << error.message() << endl;
}
else {
const char* data = boost::asio::buffer_cast<const char*>(receive_buffer.data());
cout << data << endl;
}
return 0;
}
Output:
Hello from Client!
Server sent hello message to Client!
Client sent hello message!
Hello from Server!
Comments