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.