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

Source: Internet
Author: User
Tags posix

Exception handling vs error CodeBoost.asio allows for both exception handling or error code, and all async functions have overloads that throw errors and return error codes in two ways. When a function throws an error, it often throws a boost::system::system_error error. using Boost::asio;
Ip::tcp::endpoint EP;
Ip::tcp::socket sock (service);
Sock.connect (EP); Line 1
Boost::system::error_code err;
Sock.connect (EP, err); Line 2
in the preceding code, Sock.connect (EP) throws an error, and Sock.connect (EP, err) returns an error code. Take a look at the following code snippet:try {
Sock.connect (EP);
} catch (Boost::system::system_error e) {
Std::cout << E.code () << Std::endl;
}
The following code snippet is the same as the previous one:Boost::system::error_code err;Sock.connect (EP, err);
if (ERR)
std::cout << err << Std::endl;when using an async function, you can check the error code returned in your callback. An async function never throws an exception because it makes no sense. So who's going to catch it? In your async function, you can use exception handling or error codes (whatever you want), but be consistent. Using both of these methods can cause problems and most of the time it crashes (when you accidentally make a mistake and forget to handle a thrown exception). If your code is complicated (calling many socket read-write functions), you might want to choose the exception handling method to include your read and write in a function try {} catch block. void Client_session (Socket_ptr sock) {
try {
...
} catch (Boost::system::system_error e) {
Handle the error
}
}
If you use an error code, you can use the following code snippet to see when the connection was closed:Char data[512];
Boost::system::error_code error;
size_t length = sock.read_some (buffer (data), error);
if (Error = = error::eof)
Return Connection closed
all Boost.asio error codes are included in the Boost::asio::error namespace (so that you can create a large switch to check the cause of the error). For more details, please refer to the BOOST/ASIO/ERROR.HPP header file.
threads in the Boost.asiowhen it comes to boost.asio threads, we often discuss:Io_service:io_service is thread-safe. Several threads can call Io_service::run () at the same time. In most cases, you might call Io_service::run () in a single-threaded function that must wait for all asynchronous operations to complete before you can resume execution. However, you can actually call Io_service::run () in multiple threads. This blocks all threads that call Io_service::run (). As long as any one of the threads calls Io_service::run (), all callbacks are called at the same time, which means that when you call Io_service::run () in a thread, all callbacks are called.
the Socket:socket class is not thread-safe. So, you want to avoid reading a socket in a thread while writing it in another thread. (This is usually not recommended, let alone Boost.asio). utility: As far as utility is concerned, because it is not thread-safe, it is generally not advocated for simultaneous use in multiple threads. The method is often used only in a short time, and then released. In addition to your own thread, the Boost.asio itself contains several threads. However, you can ensure that those threads do not call your code. This also means that only the thread that called the Io_service::run () method calls the callback function.
more than just network communicationIn addition to network communication, Boost.asio also contains other I/O functions. Boost.asio supports semaphores such as sigterm (software termination), SIGINT (interrupt signal), SIGSEGV (segment error), and so on. You can create an Signal_set instance that specifies the amount of semaphores to wait asynchronously, and then when these semaphores are generated, your asynchronous handler is called:void Signal_handler (const Boost::system::error_code & err, int signal)
{
Log this, and terminate application
}
Boost::asio::signal_set Sig (Service, SIGINT, SIGTERM);
Sig.async_wait (Signal_handler);
If SIGINT is generated, you will be able to capture it in your Signal_handler callback. you can use Boost.asio to easily connect to a serial port. The port name on Windows is COM7, which is/DEV/TTYS0 on the POSIX platform. Io_service Service;
Serial_port SP (Service, "COM7");
after opening the port, you can use the following code to set some port options, such as port baud rate, parity, and stop bit. serial_port::baud_rate rate (9600);
Sp.set_option (rate);
after opening the port, you can think of this serial port as a stream, and then, based on this, use the free function to read/write to the serial port. such as Async_read (), Write, Async_write (), just like the following code snippet:Char data[512];
Read (sp, buffer (data, 512));
Boost.asio can also connect to Windows files, and then also use free functions such as read (), Asyn_read (), and so on, like the following code snippet:HANDLE h =:: OpenFile (...);
Windows::stream_handle sh (service, h);
Char data[512];
Read (h, buffer (data, 512));
For Poxis file descriptors, such as pipelines, standard I/O, and various devices (but not ordinary files) you can do the same, just as the following code does:
Posix::stream_descriptor sd_in (service,::d up (Stdin_fileno));
Char data[512];
Read (sd_in, buffer (data,));
Timer
some I/O operations require a completion cutoff time. You can only apply on asynchronous operations (synchronization means blocking, so there is no deadline). For example, your next message must be delivered to you within 100 milliseconds from your companion. BOOL Read = FALSE;
void Deadline_handler (const Boost::system::error_code &) {
Std::cout << (read? "Read successfully": "Read failed") <<
Std::endl;
}
void Read_handler (const Boost::system::error_code &) {
Read = true;
}
Ip::tcp::socket sock (service);
...
Read = false;
Char data[512];
Sock.async_read_some (Buffer (data, 512));
Deadline_timer T (service, Boost::p osix_time::milliseconds (100));
T.async_wait (&deadline_handler);
Service.run ();
In the previous code snippet, if you read the data before the deadline, read is set to True so our partner notifies us in a timely manner. Otherwise, when Deadline_handler is called, read or false means that we do not meet our deadlines. Boost.asio also supports synchronous timers, when they are usually the same as a simple sleep operation. Boost::this_thread::sleep (500); This code is doing the same thing as the following code fragment:Deadline_timer T (service, Boost::p osix_time::milliseconds (500));
T.wait ();

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

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.