Boost.Asio C++ Network Programming - Wisnu Anggoro - E-Book

Boost.Asio C++ Network Programming E-Book

Wisnu Anggoro

0,0
23,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Boost.Asio is a C++ library used for network programming operations.
Organizations use Boost because of its productivity. Use of these high-quality libraries speed up initial development, result in fewer bugs, reduce reinvention-of-the-wheel, and cut long-term maintenance costs. Using Boost libraries gives an organization a head start in adopting new technologies.
This book will teach you C++ Network programming using synchronous and asynchronous operations in Boost.Asio with minimum code, along with the fundamentals of Boost, server-client applications, debugging, and more.
You will begin by preparing and setting up the required tools to simplify your network programming in C++ with Boost.Asio. Then you will learn about the basic concepts in networking such as IP addressing, TCP/IP protocols, and LAN with its topologies. This will be followed by an overview of the Boost libraries and their usage.
Next you will get to know more about Boost.Asio and its concepts related to network programming. We will then go on to create a client-server application, helping you to understand the networking concepts. Moving on, you will discover how to use all the functions inside the Boost.Asio C++ libraries. Lastly, you will understand how to debug the code if there are errors found and will run the code successfully.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 203

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Boost.Asio C++ Network Programming Second Edition
Credits
About the Authors
Acknowledgements
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Simplifying Your Network Programming in C++
Setting up the MinGW compiler and Text Editor
Installing MinGW-w64
Setting up the Path environment
Choosing and installing the Text Editor
Using the GCC C++ compiler
Compiling a C++ program
Compiling multiple source files
Compiling and linking a program separately
Detecting a warning in the C++ program
Knowing other important options in the GCC C++ compiler
Troubleshooting in the GCC C++ compiler
Help for command-line options
Version numbers
The verbose compilation
Summary
2. Understanding the Networking Concepts
An introduction to networking systems
The OSI reference model
The Physical layer
The Data Link layer
The Network layer
The Transport layer
The Session layer
The Presentation layer
The Application layer
The TCP/IP reference model
Understanding TCP and UDP
Transmission Control Protocol
User Datagram Protocol
Understanding ports
Exploring the Internet Protocol
Internet Protocol Version 4 – IPv4
Internet Protocol Version 6 – IPv6
Using TCP/IP tools for troubleshooting
The ipconfig command
Displaying the full configuration information
Displaying DNS
Flushing DNS
Renewing the IP address
Releasing the IP address
The ping command
The tracert command
The pathping command
The netstat command
The telnet command
Summary
3. Introducing the Boost C++ Libraries
Introducing the C++ standard template library
Introducing the Boost C++ libraries
Advantages of Boost libraries
Preparing Boost libraries for the MinGW compiler
Downloading Boost libraries
Deploying Boost libraries
Using Boost libraries
Building Boost libraries
Summary
4. Getting Started with Boost.Asio
Getting closer to the Boost.Asio library
Examining the I/O service in the Boost.Asio library
Using and blocking the run() function
Using the non-blocking poll() function
Removing the work object
Dealing with many threads
Understanding the Boost.Bind library
Wrapping a function invocation
Working with the Boost.Bind library
Synchronizing data access with the Boost.Mutex library
Giving some work to the I/O service
Using the post() function
Using the dispatch() function
Summary
5. Delving into the Boost.Asio Library
Serializing the I/O service work
Using the strand function
Wrapping a handler through the strand object
Handling exceptions and errors
Handling an exception
Handling an error
Timing the work execution using the timer class
An expiring timer
Using the timer along with the boost::bind function
Using the timer along with the boost::strand function
Summary
6. Creating a Client-server Application
Establishing a connection
A synchronous client
An asynchronous client
An asynchronous server
Reading and writing to the socket
The Send() and OnSend() functions
The Recv() and OnRecv() functions
Wrapping the network code
Developing a client and server program
Creating a simple echo server
Creating a simple client program
Summary
7. Debugging the Code and Solving the Error
Choosing a debugging tool
Installing a debugging tool
Preparing a file for debugging
Running the program under GDB
Starting the debugging process
The continuing and stepping debugging process
Printing the source code
Setting and deleting the breakpoint
Printing a variable value
Modifying a variable value
Calling the command prompt
Solving the error
What's next?
Summary
Index

Boost.Asio C++ Network Programming Second Edition

Boost.Asio C++ Network Programming Second Edition

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: February 2013

Second published: September 2015

Production reference: 1100915

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-307-9

www.packtpub.com

Credits

Authors

Wisnu Anggoro

John Torjo

Reviewers

Toma Becea

Iyed Bennour

Vic Taylor

Commissioning Editor

Veena Pagare

Acquisition Editor

Tushar Gupta

Content Development Editor

Rashmi Suvarna

Technical Editor

Abhishek R. Kotian

Copy Editor

Neha Vyas

Project Coordinator

Judie Jose

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Production Coordinator

Conidon Miranda

Cover Work

Conidon Miranda

About the Authors

Wisnu Anggoro is a Microsoft Certified Professional in C# programming and an experienced C/C++ developer. He has been programming since he was in junior high school, and he started developing computer applications using basic programming in the MS-DOS environment. He has good experience in smart card programming as well as desktop and web application programming, such as designing, developing, and supporting live use applications for SIM Card Operating System Porting, personalization, PC/SC communication, and other smart card applications that require the use of C# and C/C++.

He is currently a senior smart card software engineer at Cipta Srigati Lestari (www.cslgroup.co.id), an Indonesian company that specializes in the innovation and technology of smart cards. There, he holds the position of the smart card tools team leader. He has the responsibility of managing the smart card tools team and developing various applications and tools in order to create smart cards that can connect to any computer application.

Before this, he worked as a platform engineer at the same company. In this position, he successfully ported the GSM operating system from Tongfang THC20F17BD Chip (MCS51) to Xirka XSTSCSIM864 Chip (MCS51) and the RUIM operating system from Samsung S3FC9xx Chip (ARM) to EMTG97 Chip (MCS51). He also successfully developed a personalization tool for the MIFARE Classic card, a smart card key generator dongle used to activate the operating system based on the ICCID number using its own cryptography algorithm, and various smart card applications. He did this by accessing smart card readers using P/Invoke C#, RESTful applications that use HttpNet and JSON XML serialization in C#, and responsive applications that use multithreading and asynchronous processing in C#.

This is his first, and he plans to write as many books about C/C++ and C# programming in the future as possible. You can reach him through his e-mail at <[email protected]>.

Acknowledgements

First and foremost, I would like to thank God, whose many blessings have made me who I am today. To my wife, Vivin, for her constant love and support and for not letting me give up on writing this book. To my beloved son, Olav, who has given me so much happiness and has kept me hopping. To my parents and family for their inspiration.

Also, thank you to the following individuals; without their contributions and support, this book would not have been written.

The great team at Packt Publishing, especially Tushar Gupta, my acquisition editor, who invited me to author this book and guided me to start writing it. Rashmi Suvarna, my content development editor, for her efforts in making my book's content awesome. Abhishek Kotian, my technical editor, who ensured that all the source code is valid; thanks for correcting my confusing phrases.

My superiors at Cipta Srigati Lestari, Abdul Hakim and Benediktus Dwi Desiyanto, for all the knowledge you have shared—not only about technical stuff, but also about soft skills. It proved to be really helpful while I was writing this book.

Christopher Kohlhoff, the founder of Boost Asio; thanks for your video presentation on YouTube titled Thinking Asynchronously: Designing Applications with Boost.Asio, which can be found at https://www.youtube.com/watch?v=D-lTwGJRx0o.

Boris Schäling, the author of The Boost C++ Libraries and the owner of http://www.theboostcpplibraries.com; thanks for your site. It has inspired me a lot.

Drew Benton, thanks for sharing your knowledge of Boost.Asio on the gamedev.net forum at http://www.gamedev.net/blog/950/entry-2249317-a-guide-to-getting-started-with-boostasio/?pg=1.

Thanks to Harvard University for providing free lectures on GDB at http://www.sourceware.org/gdb/current/onlinedocs/gdb.html and also for providing quick and easy-to-understand videos about GDB on YouTube at https://www.youtube.com/watch?v=sCtY--xRUyI.

John Torjo is a renown C++ expert. He has been programming for over 15 years, most of which were spent doing C++. Sometimes, he also codes C# or Java. He's also enjoyed writing articles about programming in C++ Users Journal (currently, Dr. Dobbs) and other magazines. In his spare time, he likes playing poker and driving fast cars. One of his freelance projects lets him combine two of his passions, programming and poker. You can reach him at <[email protected]>.

About the Reviewers

Toma Becea is a passionate programmer and an employee at Macadamian Inc. He loves to delve into technologies such as WPF, WebRTC, and iOS. He also likes cycling, playing football, and hang gliding.

Iyed Bennour is a senior software engineer. He spent the last 10 years developing large-scale multithreading and networking C++ software in the telecommunication industry. He sees software development as a craft that needs to be mastered and likes to think of himself as a software craftsman.

Vic Taylor is a formally trained educator who received his PhD in urban education from the University of Wisconsin—Milwaukee in 1999. He has been programming since he fell in love with it in 1979, when he was still in graduate school (University of Wisconsin—Madison) and completing a data analysis that required him to learn enough of Fortran to use IMSL.

Vic has been a professional programmer/consultant for about 35 years now, and he has been contracted by Nevelex Corporation to write C++11 code for several DirecTV projects. Some of his previous accomplishments include single-handedly analyzing, designing, and implementing four major industrial control applications for Badger Meter Incorporated (Milwaukee, WI) on a contractual basis between 1994 and 2005.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

Network applications were not very easy to develop about two decades ago. But thanks to Boost.Asio, which has provided us with the network programming function as well as the asynchronous operations functionality to program a network application, we can now develop them easily. Since data transmission over a network can take a long time, which means acknowledgments and errors may not be available as fast as the functions that send or receive data can execute, the asynchronous operations functionality is really required in network application programming. In this book, you will learn the basics of networking and also how to develop a network application using the Boost.Asio libraries.

What this book covers

Chapter 1, Simplifying Your Network Programming in C++, explains the preparation of a C++ compiler, which will be used to compile all the source code in this book. Also, it will tell us how to compile a single source code and link to multiple source codes.

Chapter 2, Understanding the Networking Concepts, covers the network reference models, which are OSI and TCP/IP. It also provides various TCP/IP tools that we will often be using to detect whether an error has occurred in our network connection.

Chapter 3, Introducing the Boost C++ Libraries, explains how to set up the compiler in order to compile the code that contains the Boost libraries and how to build the binaries of libraries that we have to compile separately.

Chapter 4, Getting Started with Boost.Asio, talks about concurrent and nonconcurrent programming. It also discusses the I/O service, which is used to access the operating system's resources and establish communication between our program and the operating system that performs I/O requests.

Chapter 5, Delving into the Boost.Asio Library, walks us through how to serialize an I/O service's work in order to ensure that the order of work completely matches the order we have designed. It also covers how to handle errors and exceptions and create time delays in network programming.

Chapter 6, Creating a Client-server Application, discusses developing a server that is able to send and receive data traffic from a client and also how to create a client-side program to receive data traffic.

Chapter 7, Debugging the Code and Solving the Error, covers the debugging process to trace the errors that may be produced by an unexpected result, such as getting crash in the middle of a program execution. After reading this chapter, you will be able to solve various errors by debugging the code.

What you need for this book

To walk through this book and to successfully compile all source codes, you need a personal computer that runs Microsoft Windows 8.1 (or a later version) and contains the following software:

MinGW-w64 for Windows, version 4.9.2The latest version of Notepad++The Boost C++ libraries, version 1.58.0

Who this book is for

This book is for C++ network programmers who have basic knowledge of network programming, but no knowledge of how to use Boost.Asio for network programming.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Wait for a moment until the mingw-w64-install.exe file is completely downloaded."

A block of code is set as follows:

/* rangen.cpp */ #include <cstdlib> #include <iostream> #include <ctime> int main(void) {

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

int guessNumber;std::cout << "Select number among 0 to 10: ";std::cin >> guessNumber;

Any command-line input or output is written as follows:

rundll32.exe sysdm.cpl,EditEnvironmentVariables

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "You will be greeted by a Welcoming dialog box. Just press the Next button to go to the Setup Setting dialog box."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Simplifying Your Network Programming in C++

There are several C++ compilers that we can choose from the Web. To make it easier for you to follow all the code in this book, I have chosen a compiler that will make the programming process simpler—definitely the easiest one. In this chapter, you will discover the following topics:

Setting up the MinGW compilerCompiling in C++Troubleshooting in GCC C++

Setting up the MinGW compiler and Text Editor

This is the hardest part—where we have to choose one compiler over the others. Even though I realize that every compiler has its own strength and weakness, I want to make it easier for you to go through all the code in this chapter. So, I suggest that you apply the same environment that we have, including the compiler that we use.

I am going to use GCC, the GNU Compiler Collection, because of its widely used open source. Since my environment includes Microsoft Windows as the operating system, I am going to use Minimalistic GCC for Windows (MinGW) as my C++ compiler. For those of you who have not heard about GCC, it is a C/C++ compiler that you can find in a Linux operating system and it is included in a Linux distribution as well. MinGW is a port of GCC to a Windows environment. Therefore, the entire code and examples in this book are applicable to any other GCC flavor.

Installing MinGW-w64

For your convenience, and since we use a 64-bit Windows operating system, we chose MinGW-w64 because it can be used for Windows 32-bits and 64-bits architecture. To install it, simply open your Internet browser and navigate to http://sourceforge.net/projects/mingw-w64/ to go to the download page, and click on the Download button. Wait for a moment until the mingw-w64-install.exe file is completely downloaded. Refer to the following screenshot to locate the Download button:

Now, execute the installer file. You will be greeted by a Welcoming dialog box. Just press the Next button to go to the Setup Setting dialog box. In this dialog box, choose the latest GCC version (at the writing time this, it is 4.9.2), and the rest of the options are to be chosen, as follows:

Click on the Next button to continue and go to the installation location option. Here, you can change the default installation location. I am going to change the installation location to C:\MinGW-w64 in order to make our next setting easier, but you can keep this default location if you want.

Click on the Next button to go to the next step and wait for a moment until the files are downloaded and the installation process is complete.

Setting up the Path environment

Now you have the C++ compiler installed on your machine, but you can only access it from its installed directory. In order to access the compiler from any directory in your system, you have to set the PATH environment by performing the following steps:

Run Command Prompt as an administrator by pressing the Windows + R key. Type cmd in the text box and, instead of pressing the Enter key, press Ctrl + Shift + Enter to run the command prompt in Administrator mode. The User Account Control dialog box will then appear. Choose YES to confirm that you intend to run Command Prompt in Administrator mode. If you do this correctly, you will get a title bar labeled Administrator: Command Prompt. If you do not get it, you might not have the administrator privilege. In this case, you have to contact the administrator of your computer.Type the following command in Command Prompt in Administrator mode:
rundll32.exe sysdm.cpl,EditEnvironmentVariables
Press the Enter key and the command prompt will immediately run the Environment Variables window. Afterwards, go to System variables, select the variable named Path, click on the Edit button to open the Edit System Variable dialog box, and then append the last Variable value parameter with the following string:
;C:\MinGW-w64\mingw64\bin

(Otherwise, you will have to adjust the path of the installation directory if you use the default location the installation wizard is given in the previous step)

Click on the OK button on the Edit System Variable dialog box, and click on the OK button again in the Environment Variables dialog box to save these changes.

It is time to try our Environment Variable setting. Open a new Command Prompt window, either in Administrator or non-Administrator mode, in any active directory except C:\MinGW-w64 and type the following command:

g++ --version

You have configured the proper settings if you see the output informing you the following:

g++ (x86_64-posix-seh-rev2, Built by MinGW-W64 project) 4.9.2

If you are showed a different version number, you might have another GCC compiler on your computer. To solve this problem, you can modify Environment Variable and remove all path environment settings associated with the other GCC compiler, for instance, C:\StrawberryPerl\c\bin.

However, if you do believe that you have followed all the steps correctly, but you still get an error message, as shown in the following snippet, you might have to restart your machine for your new system settings to be set:

'g++' is not recognized as an internal or external command, operable program or batch file.

Choosing and installing the Text Editor

Microsoft Windows has been equipped with Notepad, a simple text editor to create plain text files. You can use Notepad to create a C++ file, where the file must contain only plain text formatting. You can also turn to a heavy Integrated Development Environments (IDE) when you want to edit your code, but I prefer a simple, lightweight, and extensible programming plain-text editor, so I choose to use a text editor instead of IDE. Since I will need syntax highlighting when writing code to make it easier to read and understand, I pick Notepad++ as our text editor. You can choose your favorite text editor as long as you save the output file as plain text. Here is the sample of syntax highlighting in Notepad++:

If you decide to use Notepad++ as I did, you can go to http://notepad-plus-plus.org/ to grab the latest version of Notepad++. Find the Download menu on the main page and select the current version link. There, you will find a link to download the installer file. Use the Notepad++ Installer