Boost.asio C + + Network programming translator (21)

Source: Internet
Author: User

Synchronous vs AsynchronousBoost.asio's author has done an amazing job: it allows you to choose between synchronization and asynchrony to better adapt to your application. in the previous chapters, we learned about the framework for each type of application, such as synchronous client, synchronous server, asynchronous client, and asynchronous server. Every one of you can be used as the basis for your application. If you want to learn more about the details of the various types of applications, continue.
mixed synchronous Asynchronous ProgrammingThe Boost.asio library allows you to synchronize and asynchronously mix programming. I personally think this is a bad idea, but Boost.asio (like C + +) allows you to go deep into the ground when you need it. generally speaking, 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 did 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 blocks the current thread, causing any other pending asynchronous operation to become suspended (to this thread). This is a bad code because it causes the entire application to become unresponsive or blocked (all endpoints that run asynchronously must avoid blocking, and performing a synchronous operation violates this principle). when you write a synchronous application, you are unlikely to perform asynchronous read or write operations, because thinking synchronously already means thinking in a linear way (executing a, then executing B, then C, and so on). The only thing I can think of is that synchronous and asynchronous operations are completely isolated, for example, to read and write from a database synchronously and asynchronously.
deliver information from the client to the server vs. server-to-client deliverya very important part of a successful client/server application is passing messages back and forth (service-to-client and client-to-server). You need to specify what you want to use to mark a message. In other words, when reading an input message, how do you know that it is fully read? the way you mark the end of a message depends entirely on you (marking the beginning of the message is simple, because it is the first byte passed after the previous message), but to ensure that the message is simple and continuous. You can:
    • Message size fixed (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 '/'
    • The header of the message specifies the size of the message
The way I use the whole book is to "use ' \ n ' to mark the end of a message." Therefore, each time a message is read, it will be as follows:
  1.  char buff_[512]; Synchronously reads read (Sock_, buffer (buff_),  
      Boo   St::bind (&read_complete, this, _1, _2)); Asynchronously reads  
      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) retur       n 0;       Already_read_ = bytes; BOOL found = Std::find (buff_, buff_ + bytes, ' \ n ') < buff_ +  
      bytes; One read, until read to enter, no cache return found? 0:1;  

    }&NBSP;

I assign the message length to the message header this way is left to the reader as an exercise; it is very simple.
synchronous I/O in the client appsynchronous clients can generally be categorized into one of the following two scenarios:
    • It requests something from the server, reads the results, and then processes them. Then ask for something else and then keep going. In fact, this is much like the synchronization client mentioned in the previous section.
    • Reads the message from the server, processes it, and then writes back the result. Then read another message, and then continue.

Two scenarios use the "Send request-read results" policy. In other words, one part sends a request to another section and then another part returns the result. This is a very simple way to implement a client/server application, and this is a very recommended way for me. You can create a Mambo Jambo type of client-side app, you can write any part of them as you wish, but this can lead to a disaster. (How do you know what happens when the client or server is blocked?) )。 The situation above looks similar, but they are very different:
    • The former, the service side responds to the request (the server waits for a request from the client and then responds). This is a request-only connection, and the client pulls what it needs from the server.
    • The latter, the server sends an event to the client and then responds by the client. This is a push-to-connect, server-side push notification/event to the client.
Most of the time you are doing a request-client/server-side application, which is also relatively simple, but also more common. you can combine pull requests (client-to-server) and push requests (server-to-client), but this is very complex, so you'd better avoid this. The problem with combining these two approaches is that if you use the Send request-read results policy. The following series of things can happen:Client Write (send request)Server-side write (send notification to client)The client reads the content written by the server and parses it as the result of the requestThe server is blocked to wait for the return result of the client, which occurs when the client sends a new requestThe service side interprets the sent request as the result of its waiting.The client is blocked (the server does not return any results because it treats the client's request as if it notifies the returned result)In a request-client/server-side application, it is very easy to avoid the above scenario. You can simulate a push request by implementing a ping operation, and we assume that the client pings the server every 5 seconds. If nothing needs to be notified, the server returns a ping ok result, and if something needs to be notified, the server returns a ping [Event_Name]. The client can then initialize a new request to handle the event. to review, the first scenario is the synchronization client application in the previous section, and its main loop is as follows:
void Loop () {       //For the result of our login operation       write ("login" + username_ + "\ n");       Read_answer ();       while (Started_) {
           Write_request ();           Read_answer ();           ...

} }

we modify it to accommodate the second case:
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 () {
     // ... See what the notification is and then prepare to reply   }

PS: New iteration of the attack ...





Boost.asio C + + Network programming translator (21)

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.