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

Source: Internet
Author: User

TCP Asynchronous service-sideThe core functions are similar to those of the synchronization server, as follows:
Class Talk_to_client:public Boost::enable_shared_from_this<talk_to_   client>
                        , boost::noncopyable {       typedef talk_to_client Self_type;
       Talk_to_client (): Sock_ (Service), Started_ (false) {} public   :
       typedef boost::system::error_code Error_code;       typedef boost::shared_ptr<talk_to_client> PTR;
       void Start () {           started_ = true;

Do_read (); }

       static ptr New_ () {           ptr new_ (new talk_to_client);           return new_;
       }       void Stop () {
           if (!started_) return;           Started_ = false;           Sock_.close ();
       }       Ip::tcp::socket & Sock () {return sock_;}       ...
   Private:       ip::tcp::socket sock_;       enum {max_msg = 1024x768};       Char read_buffer_[max_msg];       Char write_buffer_[max_msg];       BOOL Started_;

};

Because we are very simple echo services, there is no need for a is_started () method. For each client, just read its message, echo it, and then close it.the Do_read (), Do_write (), and Read_complete () methods are fully consistent with the TCP synchronization server. The main logic is also in the On_read () and On_write () methods:
void On_read (const Error_code & err, size_t bytes) {       if (!err) {
           std::string msg (read_buffer_, bytes);
           Do_write (msg + "\ n");       }

Stop (); }

   void On_write (const Error_code & err, size_t bytes) {       do_read ();
}
The processing of the client is as follows:
Ip::tcp::acceptor acceptor (Service, Ip::tcp::endpoint (Ip::tcp::v4 (),   8001));   void Handle_accept (talk_to_client::p TR Client, const Error_code & err)   {
       Client->start ();       Talk_to_client::p TR 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::p TR client = Talk_to_client::new_ ();       Acceptor.async_accept (Client->sock (),
           Boost::bind (handle_accept,client,_1));       Service.run ();

}

Every time a client connects to a service, handle_accept is called, it reads asynchronously from the client, and then waits for a new client equally asynchronously.
Code you will get all 4 applications in the corresponding code in this book (TCP Echo Synchronization client, TCP Echo Synchronization service side, TCP echo asynchronous client, TCP echo Async service side). When testing, you can use any client/server combination (for example, an asynchronous client and a synchronous server).
UDP echo Server/client because UDP does not guarantee that all information arrives at the receiver, we cannot guarantee that "the information ends with a carriage return". Did not receive the message, we just echo, but no socket to close (on the server), because we are UDP.
UDP synchronous Echo ClientThe UDP echo client is simpler than the TCP echo client:
Ip::udp::endpoint EP (Ip::address::from_string ("127.0.0.1"), 8001);   void Sync_echo (std::string msg) {
       Ip::udp::socket Sock (service, Ip::udp::endpoint (IP::UDP::V4 (), 0)   );
       Sock.send_to (Buffer (msg), EP);       Char buff[1024];       Ip::udp::endpoint Sender_ep;       int bytes = sock.receive_from (buffer (buff), sender_ep);       std::string copy (buff, bytes);
       Std::cout << "Server echoed our" << msg << ":"                   << (copy = = msg? ") OK ":" FAIL ") << Std::endl;
       Sock.close ();   }
   int main (int argc, char* argv[]) {       char* messages[] = {"John says hi", "so does James", "Lucy got
   Home ", 0};       Boost::thread_group Threads;       for (char * * message = messages; *message; ++message) {
           Threads.create_thread (Boost::bind (Sync_echo, *message));
           Boost::this_thread::sleep (boost::p osix_time::millisec);       }
       Threads.join_all ();   }
All logic is in Synch_echo (), connected to the server, sending messages, receiving echo from the server, and closing the connection.
UDP synchronous echo service sideThe UDP echo server will be the simplest server you've ever written:
Io_service Service;   void Handle_connections () {
       Char buff[1024];
       Ip::udp::socket Sock (service, Ip::udp::endpoint (Ip::udp::v4 (),   8001));
       while (true) {           ip::udp::endpoint sender_ep;           int bytes = sock.receive_from (buffer (buff), sender_ep);           std::string msg (buff, bytes);           Sock.send_to (Buffer (msg), SENDER_EP);

} }

   int main (int argc, char* argv[]) {       handle_connections ();

}

It's very simple, and it's self-explaining. I leave the asynchronous UDP client and the server to the reader as an exercise.
Summarize the applications that we have written to finish, and ultimately let Boost.asio work. Echo App is a great tool to start learning a library. You can often learn and run the code shown in this section so that you can easily remember the base of the library. In the next chapter, we'll build more complex client/server applications, and we'll make sure to avoid low-level errors such as memory leaks, deadlocks, and so on.



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

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.