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

Source: Internet
Author: User

Boost. Asio c ++ network programming translation (20), boost. asio Network Programming
The Asynchronous Server chart is quite complex. From Boost. Asio, You can see four arrows pointing to on_accept, on_read, on_write, and on_check_ping. That means you never know which asynchronous call is the next complete call, but you can be sure that it is one of the four operations. Now, we are asynchronous; we can continue to maintain a single thread. Accepting client connections is the simplest part, as shown below:

ip::tcp::acceptor acceptor(service, ip::tcp::endpoint(ip::tcp::v4(),   8001));   void handle_accept(talk_to_client::ptr client, const error_code & err)   {
       client->start();       talk_to_client::ptr new_client = talk_to_client::new_();       acceptor.async_accept(new_client->sock(),
                             boost::bind(handle_accept,new_client,_1));
   }   int main(int argc, char* argv[]) {
       talk_to_client::ptr client = talk_to_client::new_();       acceptor.async_accept(client->sock(),boost::bind(handle_accept,client,_1));
    service.run();}
The above code will always wait for a new client connection asynchronously (each new client connection will trigger another asynchronous wait operation ). We need to monitor the client list changed event (a new client connection or a client disconnection), and then notify all clients when the event occurs. Therefore, we need to save an array of client connections. Otherwise, unless you do not need to know all connected clients at a certain time point, you do not need such an array.
class talk_to_client; typedef boost::shared_ptr<talk_to_client>   client_ptr;   typedef std::vector<client_ptr> array;   array clients;
The connection class framework is as follows:

Class talk_to_client: public boost: enable_shared_from_this <talk_to _

Client>

                        , boost::noncopyable {       talk_to_client() { ... }
   public:       typedef boost::system::error_code error_code;       typedef boost::shared_ptr<talk_to_client> ptr;       void start() {
Started _ = true; clients. push_back (shared_from_this (); last_ping = boost: posix_time: microsec_clock: local_time (); do_read (); // first, wait for the client to connect
       }       static ptr new_() { ptr new_(new talk_to_client); return new_; }       void stop() {
           if ( !started_) return;           started_ = false;           sock_.close();           ptr self = shared_from_this();           array::iterator it = std::find(clients.begin(), clients.end(),
   self);           clients.erase(it);
           update_clients_changed();       }
       bool started() const { return started_; }       ip::tcp::socket & sock() { return sock_;}       std::string username() const { return username_; }       void set_clients_changed() { clients_changed_ = true; }       … 
private:
       ip::tcp::socket sock_;       enum { max_msg = 1024 };       char read_buffer_[max_msg];       char write_buffer_[max_msg];       bool started_;       std::string username_;       deadline_timer timer_;       boost::posix_time::ptime last_ping;       bool clients_changed_;

};

I will use talk_to_client or talk_to_server to call the connection class, so that you can better understand what I said.
Now you need to use the previous Code. It is the same as what we use in client applications. However, we have another stop () method, which is used to remove a client connection from the client array. The server continuously waits for asynchronous read operations:
void on_read(const error_code & err, size_t bytes) {       if ( err) stop();       if ( !started() ) return;       std::string msg(read_buffer_, bytes);
       if ( msg.find("login ") == 0) on_login(msg);       else if ( msg.find("ping") == 0) on_ping();       else if ( msg.find("ask_clients") == 0) on_clients();
   }   void on_login(const std::string & msg) {
       std::istringstream in(msg);       in >> username_ >> username_;       do_write("login ok\n");       update_clients_changed();
   }   void on_ping() {
       do_write(clients_changed_ ? "ping client_list_changed\n" : "ping   ok\n");
       clients_changed_ = false;   }
void on_clients() {
    std::string msg;
for(array::const_iterator b =clients.begin(),e =clients.end(); b   != e; ++b)
           msg += (*b)->username() + " ";       do_write("clients " + msg + "\n");

}

This code is easy to understand. Note that when a new client logs on, we call update_clients_changed () to mark clients_changed _ as true for all clients. Each time the server receives a request, it replies in the correct way, as shown below:
void do_ping() { do_write("ping\n"); }   void do_ask_clients() { do_write("ask_clients\n"); }   void on_write(const error_code & err, size_t bytes) { do_read(); }   void do_read() {
       async_read(sock_, buffer(read_buffer_),                   MEM_FN2(read_complete,_1,_2), MEM_FN2(on_read,_1,_2));
       post_check_ping();   }
   void do_write(const std::string & msg) {       if ( !started() ) return;       std::copy(msg.begin(), msg.end(), write_buffer_);       sock_.async_write_some( buffer(write_buffer_, msg.size()),
                               MEM_FN2(on_write,_1,_2));
   }   size_t read_complete(const boost::system::error_code & err, size_t   bytes) {
       // ... as before   }
At the end of each write operation, the on_write () method is called, which triggers another asynchronous read operation. In this way, the loop "Wait For request-reply request" will be executed continuously, until the client is disconnected or times out. Before each read operation starts, we wait for 5 seconds asynchronously to check whether the client times out. If the connection times out, we disable the connection:
void on_check_ping() {       ptime now = microsec_clock::local_time();       if ( (now - last_ping).total_milliseconds() > 5000)
           stop();       last_ping = boost::posix_time::microsec_clock::local_time();
   }   void post_check_ping() {
       timer_.expires_from_now(boost::posix_time::millisec(5000));
       timer_.async_wait( MEM_FN(on_check_ping));   }
This is the implementation of the entire server. You can run and make it work! In the code, I showed you what we learned in this chapter. To make it easier to understand, I reduced the Code a little. For example, I did not display most of the console output, even though they exist in the Code included in this book. I suggest you run these examples on your own, because reading the code from start to end can enhance your understanding of the application displayed in this chapter. To sum up, we have learned how to write some basic client/server applications. We have avoided some low-level errors such as memory leakage and deadlock. All codes are framed so that you can expand them as needed. In the following sections, we will gain a deeper understanding of the differences between synchronous and asynchronous programming using Boost. Asio, and learn how to embed your own asynchronous operations.





1st English: translate "-20 °C" into English

The following statements are acceptable:

Twenty degrees below zero centigrade.
Degree Celsius

Minus twenty degrees Celsius.

Minus twenty degrees centigrade.

This type of precipitator can be designed for more than-20 inches wc

Inch water column)
Is a pressure unit

It should be said that this type of machine is designed to work under the pressure of-20 inch water column.

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.