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

Source: Internet
Author: User

Synchronous vs Async First, asynchronous programming and synchronous programming are vastly different. In synchronous programming, all of your operations are executed sequentially, such as reading from a socket (request) and then writing (responding) to the socket. Each operation is blocked. Because the operation is blocked, in order to not affect the main program, when reading and writing a socket, it is common to create one or more threads to handle the socket input/output. As a result, synchronous server/client is usually multi-threaded. In contrast, asynchronous programming is event-driven. You start an operation, but you don't know when it will end; you just provide a callback, and when the operation ends, it calls the API and returns the result of the operation. This is second nature for programmers with extensive experience in Qt, a library used by Nokia to create cross-platform graphical user interface applications. So, in asynchronous programming, you only need one thread. Because it can be very difficult and error-prone to make changes halfway, you have to decide whether to implement network communication in a synchronous or asynchronous way at the beginning of the project (preferably at the outset). Not only is the API very different, the semantics of your program will also change completely (asynchronous network communication is often more difficult to test and debug than synchronous network communication). You need to consider the use of blocking calls and multithreading (synchronous, usually simpler), or fewer threads and event drivers (asynchronous, often more complex). The following is a basic example of a synchronous client: using Boost::asio;
Io_service Service;
Ip::tcp::endpoint EP (Ip::address::from_string ("127.0.0.1"), 2001);
Ip::tcp::socket sock (service);
Sock.connect (EP);
First, your program requires at least one Io_service instance. Boost.asio uses Io_service to interact with the input/output services of the operating system. Usually an instance of Io_service is sufficient. Then, create the address and port you want to connect to, and then build the socket. Connect the socket to your address and port. here is a simple server that uses the Boost.asio:typedef boost::shared_ptr<ip::tcp::socket> SOCKET_PTR;
Io_service Service;
Ip::tcp::endpoint EP (IP::TCP::V4 (), 2001)); Listen on 2001
Ip::tcp::acceptor ACC (service, EP);
while (true) {
Socket_ptr Sock (new Ip::tcp::socket (service));
Acc.accept (*sock);
Boost::thread (Boost::bind (client_session, sock));
}
void Client_session (Socket_ptr sock) {
while (true) {
Char data[512];
size_t len = sock->read_some (buffer (data));
if (len > 0)
Write (*sock, buffer ("OK", 2));
}
}
First, it is also necessary to have at least one Io_service instance. Then you specify the port you want to listen to, then create a sink, an object to receive client connections. in the next loop, you create a virtual socket to wait for the client to connect. Then when a connection is established, you create a thread to handle the connection. in the client_session thread, read a request from a client, parse it, and return the result. instead of creating an asynchronous client, you need to do the following things:using Boost::asio;
Io_service Service;
Ip::tcp::endpoint EP (Ip::address::from_string ("127.0.0.1"), 2001);
Ip::tcp::socket sock (service);
Sock.async_connect (EP, Connect_handler);
Service.run ();
void Connect_handler (const Boost::system::error_code & EC) {
Here we know we connected successfully
If EC indicates success
}
in the program you need to create at least one Io_service instance. You need to specify the address of the connection and create the socket. when the connection is complete (its completion handler) you are asynchronously connected to the specified address and port, that is, Connect_handler is called. when Connect_handler is called, check the error code (EC) and, if successful, you can write asynchronously to the server. Note: the Servece.run () loop runs all the time as long as the asynchronous operation remains to be resolved. In the previous example, only one such operation was performed, which is the async_connect of the socket. After that, Service.run () withdrew. each asynchronous operation has a completion handler-a function that is called after an operation is completed. The following code is a basic asynchronous serverUsing Boost::asio;
typedef boost::shared_ptr<ip::tcp::socket> SOCKET_PTR;
Io_service Service;
Ip::tcp::endpoint EP (IP::TCP::V4 (), 2001)); Listen on 2001
Ip::tcp::acceptor ACC (service, EP);
Socket_ptr Sock (new Ip::tcp::socket (service));
Start_accept (sock);
Service.run ();
void Start_accept (Socket_ptr sock) {
Acc.async_accept (*sock, Boost::bind (handle_accept, sock, _1));
}
void Handle_accept (Socket_ptr sock, const Boost::system::error_code &
ERR) {
if (err) return;
At here, you can read/write to the socket
Socket_ptr Sock (new Ip::tcp::socket (service));
Start_accept (sock);
}
in the previous code snippet, you first create a Io_service instance and then specify the port to listen to. Then, you create the receiver acc--an object that accepts a client connection, creates a virtual socket, and then asynchronously waits for the client to connect. Finally, run the asynchronous Service.run () loop. When a client connection is received, Handle_accept is called (the completion handler of the async_accept is called). If there is no error, the socket can be used for read and write operations. After using this socket, you create a new socket, and then call Start_accept () again to create another asynchronous operation "Waiting for client connections," so that the Service.run () loop remains busy.

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

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.