Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Boost.Asio C++ Network Programming Cookbook
Boost.Asio C++ Network Programming Cookbook

Boost.Asio C++ Network Programming Cookbook: Over 25 hands-on recipes to create robust and highly-efficient cross-platform distributed applications with the Boost.Asio library

eBook
€28.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Boost.Asio C++ Network Programming Cookbook

Chapter 2. I/O Operations

In this chapter, we will cover the following recipes:

  • Using fixed length I/O buffers
  • Using extensible stream-oriented I/O buffers
  • Writing to a TCP socket synchronously
  • Reading from a TCP socket synchronously
  • Writing to a TCP socket asynchronously
  • Reading from a TCP socket asynchronously
  • Canceling asynchronous operations
  • Shutting down and closing a socket

Introduction

I/O operations are the key operations in the networking infrastructure of any distributed application. They are directly involved in the process of data exchange. Input operations are used to receive data from remote applications, whereas output operations allow sending data to them.

In this chapter, we will see several recipes that show how to perform I/O operations and other operations related to them. In addition to this, we'll see how to use some classes provided by Boost.Asio, which are used in conjunction with I/O operations.

The following is the short summary and introduction to the topics discussed in this chapter.

I/O buffers

Network programming is all about organizing inter-process communication over a computer network. Communication in this context implies exchanging data between two or more processes. From the perspective of a process that participates in such communication, the process performs I/O operations, sending data to and receiving it from other participating...

Using fixed length I/O buffers

Fixed length I/O buffers are usually used with I/O operations and play the role of either a data source or destination when the size of the message to be sent or received is known. For example, this can be a constant array of chars allocated on a stack, which contain a string that represents the request to be sent to the server. Or, this can be a writable buffer allocated in the free memory, which is used as a data destination point, when reading data from a socket.

In this recipe, we'll see how to represent fixed length buffers so that they can be used with Boost.Asio I/O operations.

How to do it…

In Boost.Asio, a fixed length buffer is represented by one of the two classes: asio::mutable_buffer or asio::const_buffer. Both these classes represent a contiguous block of memory that is specified by the address of the first byte of the block and its size in bytes. As the names of these classes suggest, asio::mutable_buffer represents a writable buffer...

Using extensible stream-oriented I/O buffers

Extensible buffers are those buffers that dynamically increase their size when new data is written to them. They are usually used to read data from sockets when the size of the incoming message is unknown.

Some application layer protocols do not define the exact size of the message. Instead, the boundary of the message is represented by a specific sequence of symbols at the end of the message itself or by a transport protocol service message end of file (EOF) issued by the sender after it finishes sending the message.

For example, according to the HTTP protocol, the header section of the request and response messages don't have a fixed length and its boundary is represented by a sequence of four ASCII symbols, <CR><LF><CR><LF>, which is part of the message. In such cases, dynamically extensible buffers and functions that can work with them, which are provided by the Boost.Asio library, are very useful.

In this recipe...

Writing to a TCP socket synchronously

Writing to a TCP socket is an output operation that is used to send data to the remote application connected to this socket. Synchronous writing is the simplest way to send the data using a socket provided by Boost.Asio. The methods and functions that perform synchronous writing to the socket block the thread of execution and do not return until the data (at least some amount of data) is written to the socket or an error occurs.

In this recipe, we will see how to write data to a TCP socket synchronously.

How to do it…

The most basic way to write to the socket provided by the Boost.Asio library is to use the write_some() method of the asio::ip::tcp::socket class. Here is the declaration of one of the method's overloads:

template<
typename ConstBufferSequence>
std::size_t write_some(
const ConstBufferSequence & buffers);

This method accepts an object that represents a composite buffer as an argument, and as its name suggests, writes some...

Reading from a TCP socket synchronously

Reading from a TCP socket is an input operation that is used to receive data sent by the remote application connected to this socket. Synchronous reading is the simplest way to receive the data using a socket provided by Boost.Asio. The methods and functions that perform synchronous reading from the socket blocks the thread of execution and doesn't return until the data (at least some amount of data) is read from the socket or an error occurs.

In this recipe, we will see how to read data from a TCP socket synchronously.

How to do it…

The most basic way to read data from the socket provided by the Boost.Asio library is the read_some() method of the asio::ip::tcp::socket class. Let's take a look at one of the method's overloads:

template<
typename MutableBufferSequence>
std::size_t read_some(
    const MutableBufferSequence & buffers);

This method accepts an object that represents a writable buffer (single or composite) as...

Writing to a TCP socket asynchronously

Asynchronous writing is a flexible and efficient way to send data to a remote application. In this recipe, we will see how to write data to a TCP socket asynchronously.

How to do it…

The most basic tool used to asynchronously write data to the socket provided by the Boost.Asio library is the async_write_some() method of the asio::ip::tcp::socket class. Let's take a look at one of the method's overloads:

template<
    typename ConstBufferSequence,
    typename WriteHandler>
void async_write_some(
    const ConstBufferSequence & buffers,
    WriteHandler handler);

This method initiates the write operation and returns immediately. It accepts an object that represents a buffer that contains the data to be written to the socket as its first argument. The second argument is a callback, which will be called by Boost.Asio when an initiated operation is completed. This argument can be a function pointer, functor, or any other object that...

Introduction


I/O operations are the key operations in the networking infrastructure of any distributed application. They are directly involved in the process of data exchange. Input operations are used to receive data from remote applications, whereas output operations allow sending data to them.

In this chapter, we will see several recipes that show how to perform I/O operations and other operations related to them. In addition to this, we'll see how to use some classes provided by Boost.Asio, which are used in conjunction with I/O operations.

The following is the short summary and introduction to the topics discussed in this chapter.

I/O buffers

Network programming is all about organizing inter-process communication over a computer network. Communication in this context implies exchanging data between two or more processes. From the perspective of a process that participates in such communication, the process performs I/O operations, sending data to and receiving it from other participating...

Using fixed length I/O buffers


Fixed length I/O buffers are usually used with I/O operations and play the role of either a data source or destination when the size of the message to be sent or received is known. For example, this can be a constant array of chars allocated on a stack, which contain a string that represents the request to be sent to the server. Or, this can be a writable buffer allocated in the free memory, which is used as a data destination point, when reading data from a socket.

In this recipe, we'll see how to represent fixed length buffers so that they can be used with Boost.Asio I/O operations.

How to do it…

In Boost.Asio, a fixed length buffer is represented by one of the two classes: asio::mutable_buffer or asio::const_buffer. Both these classes represent a contiguous block of memory that is specified by the address of the first byte of the block and its size in bytes. As the names of these classes suggest, asio::mutable_buffer represents a writable buffer, whereas asio...

Using extensible stream-oriented I/O buffers


Extensible buffers are those buffers that dynamically increase their size when new data is written to them. They are usually used to read data from sockets when the size of the incoming message is unknown.

Some application layer protocols do not define the exact size of the message. Instead, the boundary of the message is represented by a specific sequence of symbols at the end of the message itself or by a transport protocol service message end of file (EOF) issued by the sender after it finishes sending the message.

For example, according to the HTTP protocol, the header section of the request and response messages don't have a fixed length and its boundary is represented by a sequence of four ASCII symbols, <CR><LF><CR><LF>, which is part of the message. In such cases, dynamically extensible buffers and functions that can work with them, which are provided by the Boost.Asio library, are very useful.

In this recipe, we will...

Left arrow icon Right arrow icon

Key benefits

  • Build highly efficient distributed applications with ease
  • Enhance your cross-platform network programming skills with one of the most reputable C++ libraries
  • Find solutions to real-world problems related to network programming with ready-to-use recipes using this detailed and practical handbook

Description

Starting with recipes demonstrating the execution of basic Boost.Asio operations, the book goes on to provide ready-to-use implementations of client and server applications from simple synchronous ones to powerful multithreaded scalable solutions. Finally, you are presented with advanced topics such as implementing a chat application, implementing an HTTP client, and adding SSL support. All the samples presented in the book are ready to be used in real projects just out of the box. As well as excellent practical examples, the book also includes extended supportive theoretical material on distributed application design and construction.

Who is this book for?

If you want to enhance your C++ network programming skills using the Boost.Asio library and understand the theory behind development of distributed applications, this book is just what you need. The prerequisite for this book is experience with general C++11. To get the most from the book and comprehend advanced topics, you will need some background experience in multithreading.

What you will learn

  • Boost your working knowledge of one of the most reputable C++ networking libraries—Boost.Asio
  • Familiarize yourself with the basics of TCP and UDP protocols
  • Create scalable and highly-efficient client and server applications
  • Understand the theory behind development of distributed applications
  • Increase the security of your distributed applications by adding SSL support
  • Implement a HTTP client easily
  • Use iostreams, scatter-gather buffers, and timers

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 25, 2016
Length: 248 pages
Edition : 1st
Language : English
ISBN-13 : 9781783986545
Languages :
Concepts :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jan 25, 2016
Length: 248 pages
Edition : 1st
Language : English
ISBN-13 : 9781783986545
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 108.97
Boost.Asio C++ Network Programming Cookbook
€41.99
Learning Boost C++
€41.99
Boost.Asio C++ Network Programming
€24.99
Total 108.97 Stars icon

Table of Contents

7 Chapters
1. The Basics Chevron down icon Chevron up icon
2. I/O Operations Chevron down icon Chevron up icon
3. Implementing Client Applications Chevron down icon Chevron up icon
4. Implementing Server Applications Chevron down icon Chevron up icon
5. HTTP and SSL/TLS Chevron down icon Chevron up icon
6. Other Topics Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(10 Ratings)
5 star 80%
4 star 10%
3 star 10%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




SuJo Feb 27, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The Boost library is really well laid out and really great for starting up a project quickly, however it takes time to get used to it and learn the ins and outs. I highly recommend this cookbook once you get your feet wet with networked communications between clients and servers. This cookbook delivers and the author knows the library rather well, and the best part is the code from the book works! Highly recommend this book.
Amazon Verified review Amazon
Amazon Customer Feb 23, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book to get familiar with Asio.Code examples form publisher's site make exploration much faster and productive.Will recommend this book if you already familiar with C++ and Boost and want to dive into C++ networking.
Amazon Verified review Amazon
José Santana Feb 20, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It's in the headline.The book contents is good, but the formatting is atrocious.
Amazon Verified review Amazon
Kalinda Mar 08, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I found this book approachable to someone totally ignorant of Boost.Asio. For younger readers, it provides useful historical background over _why_ Boost.Asio exists. For more experienced programmers, it's worth keeping around as a reference source to quickly use one of its recipes.Bonus points for using C++17 and sensible object-oriented design decisions in a networking context. Both of these were hard to find in a Boost.Asio tutorial when I first bought this book.
Amazon Verified review Amazon
sreeraj c Sep 11, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is one of the best Boost.Asio library book in the market. It teaches you things in step by step fashion. Must read I say.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.