Boost.asio C + + Network programming Translator (17)

Source: Internet
Author: User
Tags pings

client and service sidein this section, we'll learn more about using Boost.asio to build an extraordinary client and server application. You can run and test them, and when you understand them, you can use them as frameworks to construct your own applications. in the following example:
    • Client logs on to the server with a username (no password)
    • All connections are established by the client and the server responds when the client requests
    • All requests and replies end with a newline character (' \ n ')
    • For clients that do not have a ping operation for 5 seconds, the server automatically disconnects
The client can send the following request:
    • Get a list of all connected clients
    • The client can ping, when it pings, the server returns ping ok or ping client_list_chaned (in the following example, the client re-invites the list of clients to connect)
to be more interesting, we have added some difficulty:
    • Each client logs on to 6 user connections, such as Johon,james,lucy,tracy,frank and Abby
    • Each client connection randomly pings the server (randomly 7 seconds; So the server will shut down a connection from time to time)

Synchronous client/server sidefirst, we will implement synchronous applications. You will find that the code is straightforward and readable. However, the network part does not need its own thread, because all network calls are blocked.
Synchronizing ClientsThe Sync client runs the way you expect it to, connect to the server, log in to the servers, and then perform a connection loop, such as Hibernate, initiate a request, read the service-side return, and then hibernate for a while, then keep looping ...because we are in sync, so we have to keep it simple. First, connect to the server, and then loop, as follows:
Ip::tcp::endpoint EP (Ip::address::from_string ("127.0.0.1"), 8001);   void Run_client (const std::string & client_name) {
       TALK_TO_SVR client (client_name);       try {
           Client.connect (EP);
           Client.loop ();       } catch (Boost::system::system_error & err) {
           Std::cout << "Client terminated" << Std::endl;       }

}

The following code snippet shows the Talk_to_svr class:
struct TALK_TO_SVR {       talk_to_svr (const std::string & username)
           : Sock_ (Service), Started_ (True), Username_ (username) {}       void Connect (Ip::tcp::endpoint EP) {
           Sock_.connect (EP);       }
       void Loop () {           write ("login" + username_ + "\ n");           Read_answer ();           while (Started_) {
               Write_request ();               Read_answer ();               Boost::this_thread::sleep (Millisec (rand ()% 7000));

} }

       std::string username () const {return username_;}

... private:

       Ip::tcp::socket Sock_;       enum {max_msg = 1024x768};       int already_read_;       Char buff_[max_msg];       BOOL Started_;       Std::string username_;

};

in the loop, we just fill in 1 bits, a ping operation then sleep, and then read the service side of the return. We sleep randomly (sometimes more than 5 seconds) so that the server disconnects us at some point in time:
void Write_request () {       write ("ping\n");
   }   void Read_answer () {
       Already_read_ = 0;       Read (sock_, buffer (buff_),
               Boost::bind (&talk_to_svr::read_complete, this, _1, _2));       Process_msg ();
   }   void Process_msg () {
       std::string msg (buff_, already_read_);       if (Msg.find ("login") = = 0) on_login ();       else if (Msg.find ("ping") = = 0) on_ping (msg);       else if (Msg.find ("clients") = = 0) on_clients (msg);       else std::cerr << "Invalid msg" << msg << Std::endl;

}

for reading results, we use the read_complete mentioned in the previous section to ensure that we can all go to the newline character (' \ n '). Logic is in process_msg (), where we read the return of the server and distribute it to the correct method:
void On_login () {do_ask_clients ();}   void on_ping (const std::string & msg) {
       Std::istringstream in (msg);       Std::string answer;       In >> answer >> answer;       if (answer = = "Client_list_changed")
           Do_ask_clients ();
   }   void On_clients (const std::string & msg) {
       std::string clients = MSG.SUBSTR (8);
       Std::cout << username_ << ", New client list:" << clients;   }
   void Do_ask_clients () {       write ("ask_clients\n");       Read_answer ();
   }   void Write (const std::string & msg) {sock_.write_some (buffer (msg));}   size_t read_complete (const Boost::system::error_code & err, size_t   bytes) {
       // ... The same as before   }
When the read server is returning to our ping operation, if we get client_list_changed, we re-request the client list.





Boost.asio C + + Network programming Translator (17)

Related Article

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.