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

Source: Internet
Author: User

TCP vs UDP vs ICMPas I said before, not all member methods are available in all socket classes. I made a list that contains the different points of the member function. If a member function does not appear in this, then it is available in all socket classes. Name TCP UDP ICMP
Async_read_some is--
Async_receive_from-yes Yes
Async_write_some is--
Async_send_to-yes Yes
Read_some is--
Receive_from-yes Yes
Write_some is--
send_to-yes Yes
Other methodsother functions that are not related to connection and I/O are as follows:Local_endpoint (): This method returns the address of the socket local connection. Remote_endpoint (): This method returns the remote address to which the socket is connected. Native_handle (): This method returns the handler for the original socket. You only need it if you call a primitive method that is not supported by a boost.asio.non_blocking (): If the socket is non-blocking, this method returns True, otherwise false
native_non_blocking (): If the socket is non-blocking, this method returns True, otherwise false is returned. However, it is based on the native socket to invoke the local API. So generally, you don't need to call this method (Non_blocking () has cached the result); You only need to use this method when you call the Native_handle () method directly .At_mark (): This method returns true if the socket is to read an OOB data. This method is seldom used by you .
Other ConsiderationsFinally, it is important to note that a socket instance cannot be copied because the copy construction method and the = operator are inaccessible.
Ip::tcp::socket S1 (service), S2 (service);   S1 = s2; Compile times wrong   Ip::tcp::socket S3 (S1);//compile times wrong
This makes sense because each instance owns and manages a resource (the native socket itself). If we allow copy construction, the result is that we have two instances with the same native sockets, so we need to deal with the owner's problem (to have one instance ownership?). Or use reference counting? or the other way) Boost.asio choose not to allow copies (use shared pointers if you want to create a backup)
typedef boost::shared_ptr<ip::tcp::socket> SOCKET_PTR;
   Socket_ptr Sock1 (new Ip::tcp::socket (service));   Socket_ptr Sock2 (SOCK1); OK   socket_ptr Sock3;
   Sock3 = Sock1; Ok
Socket buffers
When reading and writing content from a socket, you need a buffer to hold the data that is read in and written out. Buffer memory must be valid longer than I/O operations, and you need to ensure that they are not released before the I/O operation ends.
This is easy for synchronous operations, and of course, this buffer is present at receive and send.
Char buff[512];   ...   Sock.receive (buffer (buff));   strcpy (Buff, "ok\n");   Sock.send (buffer (buff));
But in asynchronous operation it's so simple, look at the following code snippet:
Very bad code   ... void On_read (const Boost::system::error_code & err, std::size_t read_   bytes)   {...}   void Func () {
Char buff[512];
       Sock.async_receive (Buff), on_read);   }
After we call async_receive (), the buff is out of range and its memory will of course be released. When we begin to receive some data from the socket, we copy them into memory that is not already in us, it may be freed, or be re-opened by other code to store other data, and the result is: memory conflicts.
There are several solutions for the above problem:
Use global buffers
Creates a buffer and then releases it at the end of the operation
Use a Collection object to manage these sockets and other data, such as buffer arrays
The first method is obviously not very good, because we all know that using global variables is bad. Also, what if two instances use the same buffer?
Here's the second way implementation:
 
   
  
  1.  void on_read (char * ptr, const Boost::system::error_code & err, std::size_t read_bytes) {   
        Delete[] ptr; }  
      .... char * buff = new char[512];  
      sock.async_receive (buffer (buff), boost:: Bind (On_ read,buff,_1,_2)  
struct Shared_buffer {    boost::shared_array<char> buff;    int size;    Shared_buffer (size_t size): Buff (new char[size]), size (size) {    }    mutable_buffers_1 Asio_buff () const {
        Return buffer (Buff.get (), size);    }

};

When the On_read is out of range, the Boost::bind object is released,

Shared pointers are also released void On_read (Shared_buffer, const Boost::system::error_code & err,
                               std::size_t read_bytes) {}   sock.async_receive (Buff.asio_buff (), Boost::bind (on_read,buff,_1,_2));

The purpose of the Shared_buffer class to have substantial shared_array<>,shared_array<> exists is to save a copy of the Shared_buffer instance-when the last share_array< The,shared_array<> is automatically destroyed when the > element goes out of range, and that's what we want.

Because Boost.asio will keep a copy of the completion handle, it will call this completion handle when the operation is complete, so your goal is reached. The copy is a boost::bind functor that has an actual shared_buffer instance. It's very elegant!

The third option is to use a Connection object to manage sockets and other data, such as buffers, which are often the correct solution but very complex. We will discuss this approach at the end of this chapter.

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

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.