Boost: ASIO Connection Management 2

Source: Internet
Author: User

From the example in the previous section, we can get an inference. If no asynchronous I/O operations are initiated in the connection object, the connection object will be destroyed after the last callback function is executed.

I need to prove this inference. If startwork initiates an asynchronous call to wait for data after the connection is established, the connection object will not be destroyed during the waiting period.

Once the waiting data arrives, the connection object will be destroyed without subsequent I/O operations (write or read. Because boost: ASIO will internally reduce the shared_ptr reference count to 0.

Modify the connection in the previous section.Code:

Class connection {public: Connection (io_service & S): socket (s), read_buffer _ (1, 0 ){}~ Connection () {socket. Close (); cout <"~ Connection "<Endl;} void startwork () {cout <" the new connection object is starting now. "<Endl; async_read (socket, buffer (read_buffer _), boost: BIND (& connection: afterreadchar, this, _ 1 ));} void afterreadchar (error_code const & EC) {If (EC) {cout <EC. message () <Endl; return;} Char x = read_buffer _ [0]; If (x = 'A ') {cout <"correct data partitioned ed" <Endl;} else {cout <"wrong data partitioned ed, char is:" <(INT) x <Endl ;}} public: TCP: Socket socket; private: vector <char> read_buffer _;};

Note:

1. Use Vector <char> to save the read data. The constructor initializes the data to an array containing only one byte.

2. async_read initiates an asynchronous call. The callback function is a member function afterreadchar, which determines whether the read data is a and prints relevant information.

3. The if (EC) statement is used to determine whether an error exists.

We also need a testProgramTo initiate a TCP connection and send a byte of data.

The next section uses newlips to compile the test program. Because I don't want to use Java to write a bunch of tests. As for newlisp, I haven't learned it yet. Haha. Learn now.

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.