Example of synchronous socket connection in boost ASIO Library

Source: Internet
Author: User
<PRE name = "code" class = "CPP"> /////////////////////////// //////////// ASIO synchronization socket connection example // # include <iostream> # include <boost/thread. HPP> # include <boost/ASIO/io_service.hpp> # include <boost/ASIO. HPP> using namespace boost; typedef boost: ASIO: io_service ioservice; typedef boost: ASIO: IP: TCP; bool flag = true; void client () {int I = 0; while (I ++ <10) {this_thread: Sleep (posix_time: seconds (1); // The latency function try {ioservice Ios; TCP:: Socket so (IOS); TCP: endpoint EP (ASIO: IP: Address: from_string ("127.0.0.1"), 9999 ); // bind the IP address and port so of the other party. connect (EP); char STR [100] = {0}; so. read_some (ASIO: buffer (STR); // receives the message sent from the server STD: cout <"client: read from SER:" <STR <STD:: Endl;} catch (STD: exception & E) {STD: cout <E. what () <STD: Endl;} flag = false;} int main () {try {ioservice Ios; TCP: acceptor my_acceptor (IOS, TCP :: endpoint (TCP: V4 (), 9999); // server segment binding protocol and port STD: cout <my_acceptor.local_endpoint (). address () <STD: Endl; thread Tc (& client); // open a thread to execute the client while (FLAG) // the server side cyclically receives the client socket {STD :: cout <"waiting for client... "<STD: Endl; TCP: Socket mysocket (IOS); my_acceptor.accept (mysocket); mysocket. write_some (ASIO: buffer ("hahahahah"); // write data to the client} TC. join ();} catch (STD: exception & E) {STD: cout <E. what () <STD: Endl;} return 0 ;}


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.