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

Source: Internet
Author: User
Tags throw exception

Boost.asio Fundamentals This chapter covers some of the things you must know when you use Boost.asio. We will also delve deeper into asynchronous programming that is more alert and fun than synchronous programming.
This section of the network API contains the things you must know when writing Web applications using Boost.asio.
Everything in the Boost.asio namespace Boost.asio needs to be included in the namespace of Boost::asio or within its sub-namespace. Boost::asio: This is where the core classes and functions reside. The important classes are Io_service and streambuf. Similar to read, Read_at, Read_until, their asynchronous same-sex, their write and asynchronous write peers and other free functions are also here. Boost::asio::ip: This is where the network communication section resides. Important classes are address, endpoint, TCP, UDP and ICMP, and important free functions have connect and async_connect. Note that in the middle of boost::asio::ip::tcp::socket, the socket is just a typedef keyword in the middle of the Boost::asio::ip::tcp class. Boost::asio::error: This namespace contains the error code returned when I call the I/O routine Boost::asio::ssl: Contains the namespace of the SSL processing class Boost::asio:: Local: This namespace contains the POSIX attribute class Boost::asio::windows: This namespace contains classes for Windows features

IP address for IP address processing, Boost.asio provides ip::address, IP::ADDRESS_V4, and IP::ADDRESS_V6 classes.
They provide quite a number of functions. The most important ones are listed below: Ip::address (v4_or_v6_address): This function converts the address of a V4 or V6 to ip::addressip::address:from_string (str) : This function creates an address based on a IPV4 address (separated by.) or a IPV6 address (in hexadecimal notation).
Ip::address::to_string (): This function returns a friendly display of this address. Ip::address_v4::broadcast ([addr, Mask]): This function creates a broadcast address Ip::address_v4::any (): This function returns an address that can represent an arbitrary address.
Ip::address_v4::loopback (), Ip_address_v6::loopback (): This function returns the loop address (for V4/V6 Protocol) Ip::host_name () : This function returns the current host name with the string data type. In most cases you will choose to use ip::address::from_string. Ip::address addr = ip::address::from_string ("127.0.0.1"); If you want to connect to a host name, Continue reading. The following code fragment does not work://Throws an exception
Ip::address addr = ip::address::from_string ("www.yahoo.com");
An endpoint endpoint is an address that you connect to with a port. Different types of sockets have their own endpoint classes, such as Ip::tcp::endpoint, Ip::udp::endpoint, and Ip::icmp::endpoint. If you want to connect to the 80 port of this machine, you can do this: Ip::tcp::endpoint EP (Ip::address::from_string ("127.0.0.1"), 80); There are three ways to set up an endpoint: endpoint () : This is the default constructor, which can sometimes be used to create UDP/ICMP sockets.
Endpoint (protocol, port): This is often used to create server-side sockets that can accept new connections.
Endpoint (addr, port): This creates an endpoint that connects to a port on an address. Examples are as follows: Ip::tcp::endpoint EP1;
Ip::tcp::endpoint EP2 (Ip::tcp::v4 (), 80);
Ip::tcp::endpoint ep3 (ip::address::from_string ("127.0.0.1), 80);
If you want to connect to a host (not an IP address), you need to do this://output "87.248.122.122"
Io_service Service;
Ip::tcp::resolver Resolver (service);
Ip::tcp::resolver::query query ("www.yahoo.com", "80");
Ip::tcp::resolver::iterator iter = resolver.resolve (query);
Ip::tcp::endpoint EP = *iter;
Std::cout << ep.address (). to_string () << Std::endl;
You can replace TCP with the type of socket you need. First, create a query that you want to name, and then use the Resolve () function to parse it. If successful, he will return at least one entrance. Use the returned iterator, or use the first entry, or iterate over the entire list. To point to an endpoint that can get his address, port and IP protocol (v4 or V6):std::cout << ep.address (). to_string () << ":" << Ep.port ()
<< "/" << Ep.protocol () << Std::endl;
SocketsBoost.asio has three types of socket classes: IP::TCP, IP::UDP and ip::icmp, and of course it is extensible. You can create your own socket class, although this is quite complex. If you choose to do this, refer to Boost/asio/ip/tcp.hpp, BOOST/ASIO/IP/UDP.HPP and BOOST/ASIO/IP/ICMP.HPP. These are super-small classes that have internal typedef keywords. you can take ip::tcp, IP::UDP, ip::icmp classes as placeholders; they allow you to easily access other classes/functions as follows:Ip::tcp::socket, Ip::tcp::acceptor, Ip::tcp::endpoint,ip::tcp::resolver, Ip::tcp::iostream
Ip::udp::socket, Ip::udp::endpoint, Ip::udp::resolverIp::icmp::socket, Ip::icmp::endpoint, Ip::icmp::resolverthe socket class creates a corresponding socket. And you always pass in the Io_service instance when you construct it:
Io_service Service;
Ip::udp::socket Sock (service)
Sock.set_option (Ip::udp::socket::reuse_address (true));
each socket name is a typedef keyword? ip::tcp::socket = basic_stream_socket<tcp>
? Ip::udp::socket = basic_datagram_socket<udp>
? Ip::icmp::socket = basic_raw_socket<icmp>
Synchronization Error codeall synchronization functions have overloads that throw an exception or return an error code, such as the following code snippet:Sync_func (arg1, arg2 ... argN); Throw exception
Boost::system::error_code EC;
Sync_func (arg1 arg2, ..., ArgN, EC);//Return error codeIn the remainder of this chapter, you will see a large number of synchronization functions. For simplicity's sake, I omitted the overloads that return the error code, but they are there.
Socket member functions These functions are divided into groups. Not all functions are available in each type of socket. The end of this section will have a list of which functions belong to which socket class. Note that all asynchronous functions return immediately, and their relative synchronization implementations require the operation to be completed before they can be returned.
Connection-related functions these are functions that connect or bind sockets, disconnect socket connections, and query whether the connection is active or inactive: Assign (protocol,socket): This function assigns a native socket to the socket instance. Use it when dealing with old (old) programs (that is, the native sockets have been established)
Open (Protocol): This function opens a socket with the given IP protocol (v4 or V6). You are primarily using UDP/ICMP sockets, or service-side sockets. Bind (Endpoint): This function binds to an address of Connect (endpoint): This function is connected to an address Async_connect (endpoint) in a synchronous way: This function is connected asynchronously to an address is_open ( ): If the socket is already open, this function returns Trueclose (): This function closes the socket. Any asynchronous operation on this socket will be immediately closed and return the error::operation_aborted error code shutdown (type_of_shutdown): This function immediately invalidates the send or receive operation. Or both of them fail. Cancel (): This function cancels all asynchronous operations on this socket. Any asynchronous operation on the socket ends immediately, and then returns the error::operation_aborted error code. Examples are as follows: Ip::tcp::endpoint EP (Ip::address::from_string ("127.0.0.1"), 80);
Ip::tcp::socket sock (service);
Sock.open (Ip::tcp::v4 ()); N
Sock.connect (EP);
Sock.write_some (Buffer ("get/index.html\r\n"));
Char buff[1024]; Sock.read_some (buffer (buff,1024));
Sock.shutdown (ip::tcp::socket::shutdown_receive);
Sock.close ();

Read and write functions these are functions that perform I/O operations on sockets for asynchronous functions, the handler's signature void handler (const boost::system::error_code& E, size_t bytes) is the same async_ Receive (buffer, [flags,] handler): This function initiates the operation of the asynchronous receive data from the socket. Async_read_some (Buffer,handler): This function is the same as the async_receive (buffer, handler) function. Async_receive_from (buffer, endpoint[, flags], handler): This function initiates the operation of asynchronous receive data from a specified endpoint. Async_send (buffer [, flags], handler): This function initiates the function of an asynchronous send buffer data. Async_write_some (buffer, handler): This function is consistent with the Async_send (buffer, handler) function.
Async_send_to (buffer, endpoint, handler): This function initiates the function of an asynchronous send buffer data to the specified endpoint. Receive (buffer [, flags]): This function asynchronously reads data from the given buffer. This function is blocked until all data has been read or the error has occurred. Read_some (buffer): This function has the same function as receive (buffer). Receive_from (buffer, endpoint [, flags]): This function asynchronously fetches data from a specified endpoint and writes to the given buffer. This function is blocked until all data has been read or the error has occurred. Send (buffer [, flags]): This function synchronously sends data to the buffer. This function is blocked until all data has been sent successfully or an error has occurred.
Write_some (buffer): This function is consistent with the function of send (buffer). Send_to (buffer, endpoint [, flags]): This function synchronously sends the buffer data to a specified endpoint. This function is blocked until all data has been sent successfully or an error has occurred. Available (): This function returns how many bytes of data can be read synchronously and without blocking. We'll discuss the buffer later. Let's take a look at the markup first. The default value of the tag is 0, but it can also be of the following types: Ip::socket_type::socket::message_peek: This flag only monitors messages. It returns this message, but the next time the call to read the message reads the message again.
Ip::socket_type::socket::message_out_of_band: This tag handles out-of-band (OOB) data, and OOB data is data that is marked as more important than normal data. The discussion about OOB is outside the content of this book.
Ip::socket_type::socket::message_do_not_route: This tag specifies that the data is not sent using the routing table. Ip::socket_type::socket::message_end_of_record: This tag specifies the data that identifies the end of the record. Not supported under Windows.
You are most likely to use Message_peek, if used please refer to the following code snippet: Char buff[1024];
Sock.receive (Buff), ip::tcp::socket::message_peek);
memset (buff,1024, 0);
Re-reads what was previously read
Sock.receive (buff); Here are some examples that tell you how to read data synchronously or asynchronously from different types of sockets: Example 1 is a synchronous read/write to a TCP socket: Ip::tcp::endpoint EP (IP:: Address::from_string ("127.0.0.1"), 80);
Ip::tcp::socket sock (service);
Sock.connect (EP);
Sock.write_some (Buffer ("get/index.html\r\n"));
Std::cout << "bytes available" << sock.available () << Std::endl;
Char buff[512];
size_t read = sock.read_some (buffer (buff));
Example 2 is to read a UDP socket for synchronous reads and writes: Ip::udp::socket sock (service);
Sock.open (Ip::udp::v4 ());
Ip::udp::endpoint Receiver_ep ("87.248.112.181", 80);
Sock.send_to (Buffer ("testing\n"), RECEIVER_EP);
Char buff[512];
Ip::udp::endpoint Sender_ep;
Sock.receive_from (Buff), SENDER_EP);
[? Note: As shown in the code snippet above, when using Receive_from to read from a UDP socket, you need a default constructed endpoint] Example 3 is the asynchronous reading of data from a UDP service socket: using namespace Boost::asio;
Io_service Service;
Ip::udp::socket sock (service);
Boost::asio::ip::udp::endpoint Sender_ep;
Char buff[512];
void On_read (const Boost::system::error_code & err, std::size_t
Read_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::endpoint EP (Ip::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 (Buffer (buff,512), Sender_ep, On_read);
Service.run ();
}


Socket control: These functions are used to handle the advanced options for Sockets: Get_io_service (): This function returns the Io_service instance passed in the constructorget_option (option): This function returns the properties of a socketset_option (option): This function sets the properties of a socketIo_control (cmd): This function executes an I/O directive on a socketthese are the socket options you can get/set:Name Description Typebroadcast If TRUE, allows message bool to be broadcast
Debug                           If true, enable socket-level debugging &NBSP;&N bsp;                                   booldo_not_route                    If true, block route selection using only the local interface                              Boolenable_ connection_aborted       If true, logs an interrupted connection at accept ()                                 boolkeep_alive                     If true, Heartbeat is sent &nbsp ;                                               boollinger                            if true, the socket suspends close () if there is no data sent ()               boolreceive_buffer_size             Socket receive buffer size                                                    Intreceive_low_watemark           Specify minimum byte count for socket input processing                                         intreuse_address                   If True, Sockets can be bound to a used address                              boolsend_buffer_size               Socket send buffer size                          /                     intsend_low_watermark         &N Bsp   Specify the minimum number of bytes sent by the socket data                                         Intip::v6_only                    If true, only IPv6 connections are allowed                                         BOOL Each name represents an internal socket typedef or class. The following is the use of them: Ip::tcp::endpoint EP (Ip::address::from_string ("127.0.0.1"), 80);
Ip::tcp::socket sock (service);
Sock.connect (EP);
TCP socket can reuse address
Ip::tcp::socket::reuse_address RA (true);
Sock.set_option (RA);
Get sock Receive buffer size
Ip::tcp::socket::receive_buffer_size RBS;
Sock.get_option (RBS);
Std::cout << rbs.value () << Std::endl;
Set sock ' s buffer size to 8192
Ip::tcp::socket::send_buffer_size SBS (8192);
Sock.set_option (SBS);
[? The socket is to be opened before the above features work.] Otherwise, an exception will be thrown]

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

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.