23,99 €
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:
Seitenzahl: 203
Veröffentlichungsjahr: 2015
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
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
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]>.
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]>.
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.
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.
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.
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.
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.
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:
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.
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:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
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."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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.
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.
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.
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 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.
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.
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:
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.
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.
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:
(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:
You have configured the proper settings if you see the output informing you the following:
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:
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