C + + Boost::asio programming-synchronous TCP detailed and instance code

Source: Internet
Author: User
Boost::asio Programming-Synchronizing TCP

Boost.asio Library is a cross-platform network and the underlying IO C + + programming library, which uses modern C + + techniques to implement a unified asynchronous call model.

The Boost.asio library supports TCP, UDP, and ICMP communication protocols.

The following describes the synchronous TCP mode:

Hello everyone! I am the sync mode!

My main feature is perseverance! All the operation to complete or error will return, but my obsession is called blocking, it is depressed ~ ~ (a hiss), in fact, this is also good, such as logic clear, programming easier.

On the server side, I will make a socket to the Acceptor object, so that it has been waiting for the client to connect, and then through the socket and the client to communicate, and all the communication is blocked mode, read or write to return.

On the client side also, I will take the socket to connect to the server, of course, it is connected or wrong to return, and finally in a blocking way and the server communication.
Some people think that synchronous mode is not efficient asynchronous way, in fact, this is one-sided understanding. In the case of a single thread, it may be true that I cannot use time-consuming network operations to do something else, not a good overall approach. However, this problem can be avoided by multithreading, such as on the server side to allow one thread to wait for the client to connect, connect the socket to another thread to communicate with the client, so as to communicate with a client can also accept the connection of other clients, the main thread is completely liberated.

My introduction will have here, thank you!

Synchronous Mode Sample code:

Server-side

BoostTcpServer.cpp: Defines the entry point of the console application. #include "stdafx.h" #include "boost/asio.hpp" #include "boost/thread.hpp" using namespace std;    using namespace Boost::asio; #ifdef _msc_ver #define _WIN32_WINNT 0x0501//Avoid VC compile warning #endif #define PORT #define IPV6//#define IPV4 int _t      Main (int argc, _tchar* argv[]) {//All ASIO classes need Io_service object Io_service Iosev; Create a Acceptor object to receive client connections #ifdef IPV4 ip::tcp::acceptor acceptor (Iosev,ip::tcp::endpoint (IP::TCP::V4 (), PORT)); #endif #ifdef IPV6 ip::tcp::acceptor acceptor (Iosev,ip::tcp::endpoint (IP::TCP::V6 (), PORT));     #endif while (true) {//Socket object Ip::tcp::socket socket (Iosev);     Wait until the client connects in acceptor.accept (socket);     Show connected clients std::cout << "Remote IP:" <<socket.remote_endpoint (). Address () <<endl;        Std::cout << "Remote port:" <<socket.remote_endpoint (). Port () << Std::endl;     Char buf[2048];     Boost::system::error_code EC;     while (1){socket.read_some (buffer (BUF), EC);         if (EC) {Std::cout <<boost::system::system_error (EC). What () << Std::endl;       break;       } std::cout<< "recv msg:" <<buf<<endl;       if (strcmp (buf, "Bye") ==0)//Receive End Message end client connection {break;       } socket.write_some (Buffer ("I heared you!\n"), EC);         if (EC) {Std::cout <<boost::system::system_error (EC). What () << Std::endl;       break;     }} socket.close (); Loop continues to wait for the next customer connection after the current customer interaction is completed} return 0; }

Client

BoostTcpClient.cpp: Defines the entry point of the console application.    #include "stdafx.h" #include "boost/asio.hpp" using namespace Boost::asio; #ifdef _msc_ver #define _WIN32_WINNT 0x0501//Avoid VC compile warning #endif #define PORT #define IPV6//#define IPV4 int _t   Main (int argc, _tchar* argv[]) {//All ASIO classes need Io_service object Io_service Iosev;      Socket Object Ip::tcp::socket socket (Iosev); The connection endpoint, where the native connection is used, can modify the IP address to test the remote connection #ifdef IPV4 ip::address_v4 address=ip::address_v4::from_string ("127.0.0.1"); #endif #ifdef IPV6//"0:0:0:0:0:0:0:1" is the native loopback address of IPV6, similar to "127.0.0.1" Ip::address_v6 Address=ip::address_v6::from_strin G ("0:0:0:0:0:0:0:1");   #endif Ip::tcp::endpoint EP (address, PORT);   Connection Server Boost::system::error_code EC;   Socket.connect (EP,EC);     If error occurs, print error message if (EC) {Std::cout << boost::system::system_error (EC). What () << Std::endl;   return-1;     }//Loop send and receive data for (int i=0;i<5;++i) {//Send data Socket.write_some (buffer ("Hello"), EC);    Receive data Char buf[100];     size_t len=socket.read_some (Buffer (BUF), EC);     Std::cout.write (buf, Len);   Sleep (500);        }//Send a closing agreement with the service side, by the service side broken chain socket.write_some (buffer ("Bye"), EC);   GetChar (); return 0; }

The code is compatible with the IPV4 and IPV6 two IP protocols, using the macro definition to choose which IP protocol to use, of course, the client and server protocols must be consistent to communicate properly.

Thank you for reading, hope to help everyone, more relevant articles please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.