Boost.asio Foundation (ii)

Source: Internet
Author: User

Socket Sockets

Boost.asio has three types of socket classes: IP::TCP,IP::UDP and ip::icmp, all of which are extensible. You can create your own socket class, although it is slightly more complex to do. If you really want to do this, you can refer to BOOST/ASIO/IP/TCP.HPP,BOOST/ASIO/IP/UDP.HPP and boost/asio/ip/icmp.hpp. They are very small classes that use typedef keywords internally.
You can use the IP::TCP,IP::UDP and IP::ICMP classes as a placeholder; You can access the methods of classes and classes in the following form:

    • Ip::tcp::socket, Ip::tcp::acceptor, Ip::tcp::endpoint, Ip::tcp::resolver, Ip::tcp::iostream
    • Ip::udp::socket, Ip::udp::endpoint, Ip::udp::resolver
    • Ip::icmp::socket, Ip::icmp::endpoint, Ip::icmp::resolver

The corresponding socket class creates a corresponding socket. In Io_service instance construction, you need to pass in this socket:

io_service service;ip::udp::socket sock(service);sock.set_option(ip::udp::socket::reuse_address(true));

Each socket name comes from a typedef:

    • Ip::tcp::socket = Basic_stream_socket
    • Ip::udp::socket = Basic_stream_socket
    • Ip::icmp::socket = Basic_stream_socket
Synchronization error code (synchronous error codes)

All synchronization functions have exceptions, they throw exceptions or return an error code, such as the following code:

...... , argN, ec); //返回错误代码

In the following, you will encounter many synchronization functions. In order to remain concise, exceptions to the return error code are ignored later.

Socket member functions

These functions are divided into several groups. Not every kind of socket has access to all of these member functions. At the end of this section, there will be a table that lists which members are affiliated to which socket class.
It is important to note that all asynchronous functions are returned immediately, while the synchronous version of the function is returned only after the operation has completed.

Connection-related classes

Some functions are used to connect or bind a socket, disconnect, and query whether the connection is valid:

    • Assign (protocol, socket): It assigns the original socket (native) to the socket instance. Use it to handle some legacy systems in which sockets are usually already created.
    • Open (Protocol): Opens a socket with the given IP protocol (v4 or V6). Used primarily for UDP/ICMP sockets, or for server-side sockets.
    • Bind (Endpoint): binds to the specified address.
    • Connect (Endpoint): Synchronizes the connection to the specified address.
    • Async_connect (Endpoint): asynchronously connects to the specified address.
    • Is_open (): Whether the socket is open.
    • Close (): Closes the socket. Any asynchronous operation in this socket will be canceled and completed with the error::operation_aborted error code.
    • Shutdown (Type_of_shutdown): Disables send,receive operation.
    • Cancel (): Cancels all asynchronous operations on the socket. All asynchronous operations on this socket are immediately completed and returned with the error::operation_aborted error code.
      Here is an example:
IP:: TCP:: EndpointEpIP:: Address:: from_string("127.0.0.1"), the);IP:: TCP:: SocketSock (service); Sock.open (IP:: TCP:: V4()); Sock.connect (EP); Sock.write_some (Buffer ("get/index.html\r\n")); Char buff[1204];sock.read_some (in buffer (buff,1024x768)); Sock.shutdown (IP:: TCP:: Socket:: Shutdown_receive); Sock.close ();
Read/write functions

The read-write function makes I/O operations on the socket.
For asynchronous functions, handler is a callback function that is shaped like void handler (const boost::system::error_code& E, size_t bytes).

  • async_receive (buffer, [flags], handler): begins an asynchronous recevie operation on the socket.
  • Async_read_some (buffer, handler): same as async_receive function.
  • Async_receive_from (buffer, endpoint [, flags], handler: begins an asynchronous receive operation on the specified endpoint.
  • Async_send (buffer [, flags], handler): sends the data in the buffer asynchronously.
  • Async_write_some (buffer, handler): same as Async_send.
  • Async_send_to (buffer, endpoint, handler): begins an asynchronous send operation on the specified endpoint.
  • Receive (buffer [, flags]): synchronously accepts data to buffer, blocking it, knowing that the data has been received or is in error.
  • Read_some (buffer): same as receive.
  • Receive_from (buffer, endpoint [, flags]): receives data from a given endpoint, blocks, knows that the data is received, or is faulted.
  • Send (buffer [, flags]): synchronizes the data in the send buffer, will block, know that the data is sent to completion, or error.
  • Write_some (buffer): same as send.
  • Send_to (buffer, endpoint [, flags]): synchronously sends data to the specified endpoint. Will block, knowing that the data is being sent or error.
  • Available (): Returns the number of bytes that can be read from the socket without blocking.

Here is a brief discussion of the next buffer. The default flags parameter is 0, or you can mix the following values:

    • Ip::socket_type::socket::message_peek: This flag indicates that data is retrieved only in the buffer. It can return a message, but the next time it reads, it will reread the data.
    • Ip::socket_type::socket::message_out_of_band: This flag indicates processing out-of-band data (OBB). OBB data is more important than normal data. The discussion of OBB data is beyond the scope of this book.
    • Not supported under Ip::socket_type::socket::message_end_of_record:windows.

Most of the time we use Message_peek, as in the following example:

char buff[1024];sock.receive(buffer(buff), ip::tcp::socket::message_peek);memset(buff, 1024, 0);//重新读取上次读取过的数据sock.receive(buffer(buff));

The following example shows the difference between synchronous and asynchronous:

    • Example 1, synchronous write and read on the TCP socket:
IP:: TCP:: EndpointEpIP:: Address:: from_string("127.0.0.1", the);IP:: TCP:: SockeSock (service); Sock.connect (EP); Sock.write_some (Buffer ("get/index.html\r\n");std::cout<< "Number of valid bytes:"<< sock.available () <<std:: Endl; Char buff[ +];size_t read = sock.read_some (buffer (buff));
    • Example 2, asynchronous read and write on a UDP socket:
ip:   : UDP  :  :socket  sock (service); Sock.open ( Span class= "Hljs-symbol" >ip:  :udp  :  :v4  ()); ip:  :udp  :  :endpoint  receiver_ep ( "xxx.xxx.xxx.xxx" , 80 ) sock.send_to (buffer (), RECEIVER_EP); Char buff[512 ]; ip:  :udp  :  :endpoint  sender_ep;sock.receive_from (buffer (buff), sender_ep);  
    • Example 3, asynchronously read from the UDP server socket:
Using namespaceBoost:: ASIO; Io_service Service;IP:: UDP:: SocketSock (service);Boost:: ASIO:: IP:: UDP:: EndpointSender_ep;char buff[ +];void On_read (constBoost:: System::error_code&Errstd:: size_tRead_bytes) {std::cout<<"read"<<Read_bytes <<std:: Endl; Sock.async_receive_from (Buff), Sender_ep, on_read);} int main (int argc, char** argv) {IP:: UDP:: EndpointEpIP:: Address:: from_string("127.0.0.1"),8001);    Sock.open (Ep.protocol ()); Sock.set_option (Boost:: ASIO:: IP:: UDP:: Socket:: Reuse_address(true));    Sock.bind (EP); Sock.async_receive_from (in buffer (buff, +), Sender_ep, On_read); Service.run ();return 0;}

Boost.asio Foundation (ii)

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.