Boost. Asio c ++ network programming translation (21), boost. asio Network Programming

Source: Internet
Author: User

Boost. Asio c ++ network programming translation (21), boost. asio Network Programming
The author of synchronous VS asynchronous Boost. Asio made a very amazing job: it allows you to freely choose between synchronous and asynchronous, so as to better adapt to your application. In the previous sections, we learned the frameworks of each type of application, such as synchronous clients, synchronous servers, asynchronous clients, and asynchronous servers. Every one of you can serve as the basis of your application. If you want to learn more about various types of applications, continue.
The Boost. Asio library allows you to implement synchronous and asynchronous hybrid programming. I personally think this is a bad idea, but Boost. Asio (just like C ++) allows you to go deep into the underlying layer when you need it. Generally, when you write an asynchronous application, you can easily fall into this trap. For example, in response to an asynchronous write operation, assume that you have performed a synchronous read operation:

io_service service;   ip::tcp::socket sock(service);   ip::tcp::endpoint ep( ip::address::from_string("127.0.0.1"), 8001);   void on_write(boost::system::error_code err, size_t bytes) {
     char read_buff[512];
     read(sock, buffer(read_buff));   }
   async_write(sock, buffer("echo"), on_write);
There is no doubt that the synchronous read operation will block the current thread, resulting in any other waiting asynchronous operation being suspended (for this thread ). This is a bad piece of code, because it will cause the entire application to become unresponsive or blocked (all asynchronous running endpoints must avoid blocking, but executing a synchronization operation violates this principle ). When you write A synchronous application, you are unlikely to execute asynchronous read or write operations, because synchronous thinking already means using A linear approach (execute A, then execute B, execute C, and so on ). The only scenario I can think of is that synchronous and asynchronous operations are completely isolated, for example, synchronous and asynchronous read/write from a database.
A very important part of transferring information from a client to a server VS from a server to a client/server application that is successful on the client is to transmit messages back and forth (from the server to the client and from the client to the server ). You need to specify what to mark a message. In other words, when reading an input message, how do you determine that it is completely read? The method for marking the end of a message depends on you (the start of marking a message is very simple, because it is the first byte passed after the previous message ), however, ensure that messages are simple and continuous. You can:
  • Fixed Message Size (this is not a good idea. What if we need to send more data ?)
  • Mark the end of a message with a special character, such as '\ n' or' \ 0'
  • Specify the size of the message in the message header.
The methods I used in the entire book are "marking the end of a message with '\ N ". Therefore, each time you read a message, it will be as follows:
  1. Char buff _ [512]; // synchronously reads read (sock _, buffer (buff _),
    Boost: bind (& read_complete, this, _ 1, _ 2); // asynchronous read
       async_read(sock_, buffer(buff_),MEM_FN2(read_complete,_1,_2), MEM_FN2(on_read,_1,_2));
       size_t read_complete(const boost::system::error_code & err, size_t   bytes) {
           if ( err) return 0;       already_read_ = bytes;       bool found = std::find(buff_, buff_ + bytes, '\n') < buff_ +
    Bytes; // read one by one until the carriage return is read, no cache return found? 0: 1;

    }

I leave the method of specifying the message length in the message header as an exercise for the reader; it is very simple.
Synchronization I/O synchronization clients in client applications can be classified into one of the following two situations:
  • It requests something from the server, reads the results, and then processes them. Request other things and continue. In fact, this is similar to the synchronization client mentioned in the previous chapter.
  • Read the message from the server, process it, and write back the result. Then read another message and continue.

Both use the "Send request-read result" policy. In other words, one part sends a request to another part and then the other part returns the result. This is a very simple way to implement client/server applications, and it is also a recommended method. You can create a client server application of the Mambo Jambo type. You can write any part of the application as you like, but this will lead to a disaster. (How do you know what will happen when the client or server is blocked ?). The above situations seem similar, but they are very different:
  • The former is that the server responds to the request (the server waits for the request from the client and then responds ). This is a request-type connection. The client Pulls what it needs from the server.
  • The latter, the server sends the event to the client and then the client responds. This is a push connection. The server pushes notifications/events to the client.
Most of your time is for request-type client/server applications, which is also relatively simple and common. You can combine pull requests (from the client to the server) with push requests (from the server to the client). However, this is very complicated, so you 'd better avoid this situation. The problem with combining these two methods is that if you use the "Send request-read result" policy. The following process occurs: the client writes (sends requests), the server writes (sends notifications to the client), and the client reads the content written by the server, then, parse the request result as the server block to wait for the result returned by the client, when the client sends a new request, the server will block the resolution of the request as the result it waits for (the server will not return any results, because it regards the client request as the result returned by the notification) in a request-type client/server application, it is very easy to avoid the above situation. You can implement a ping operation to simulate a push request. We assume that the client can ping the server every five seconds. If nothing needs to be notified, the server returns a result similar to ping OK. If something needs to be notified, the server returns a ping [event_name]. Then the client can initiate a new request to process the event. Review. The first case is the synchronization client application in the previous section. Its main cycle is as follows:
Void loop () {// write ("login" + username _ + "\ n"); read_answer (); while (started _){
           write_request();           read_answer();           ...

}}

We modify it to adapt to the second situation:
void loop() {       while ( started_) {
           read_notification();
           write_answer();       }
   }   void read_notification() {
       already_read_ = 0;       read(sock_, buffer(buff_),
               boost::bind(&talk_to_svr::read_complete, this, _1, _2));       process_notification();
   }   void process_notification() {
//... View the notification and prepare a reply}

PS: new iterations are coming again...






21st)

Twenty-first

Translation speed of 21 pages in grade 7

It's a full-page translation.

Part c
1a Reading Comprehension
Read the short text and determine whether the message is correct or not.
My school life
Hi! My name is Hu Bin, a Class 7 student. At school, my teachers and classmates are very nice to me. My school life is very interesting. I like it very much.
Class started at eight o'clock A.M. I have four classes in the morning and two classes in the afternoon. I have studied Chinese, English, politics, art, history, geography, biology, and other disciplines. english is my favorite subject. I often speak English with my classmates. I also like sports and music. But I do not like mathematics very much. I think it is a bit difficult and boring. What do you think?
After school, I often play basketball with my classmates. This is my favorite outdoor exercise. Sometimes, I go swimming in the swimming pool. Sometimes, I go to the park with my friends to draw pictures. On Tuesday and Thursday, I go to the school library to read books.
Do you think my school life is interesting? What about you? Can you tell me your school life?

1. Hu Bin enjoys his campus life very much. ()
2. Mathematics is Hu Bin's favorite subject. ()
3. Hu Bin has six classes every day from Monday to Friday. ()
4. He goes swimming on Tuesday and Thursday every week. ()
1b independent exercises
Fill in the blank according to 1a.
Hu Bin is a Class 1 student in the seventh grade. his school life is very (). Eight o'clock A.M. () class. He () Chinese, English, politics and other subjects. He is the most () English. But he is not very () in mathematics. It's a little difficult and boring. After school, he often plays basketball with his classmates. It is his favorite outdoor exercise.

Sorry, the answer was so late that I just saw it.
Hope to be accepted!
 

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.