3. boost asio tutorial---the simplest server

According to Wikipedia,

A server is a computer program or device that provides functionality for other programs or devices, called "clients."

This is a very good description, and in fact, the server is nothing more than that. There's nothing really magical about the server, it's just an application that receives data sent by other applications and returns some data.

We'll start with the simplest server - a UDP echo server. It does the following:

Receive any data sent to UDP port 15001

Send the received data back to the sender intact.

In fact, you can choose almost any port for your server. A list of many common ports used for different services can be found here: TCP and UDP port numbers However, usually, only a few of these services are used simultaneously on the machine where the operating system is installed.

Now take a look at the following source code:

#include <boost/asio.hpp>

int main() { 
    std::uint16_t port = 15001;

    boost::asio::io_context io_context;
    boost::asio::ip::udp::endpoint receiver(boost::asio::ip::udp::v4(), port);
    boost::asio::ip::udp::socket socket(io_context, receiver);

    for(;;)
    {
        char buffer[65536];
        boost::asio::ip::udp::endpoint sender;
        std::size_t bytes_transferred = socket.receive_from(boost::asio::buffer(buffer), sender);
        socket.send_to(boost::asio::buffer(buffer, bytes_transferred), s

おすすめ

転載: blog.csdn.net/Knowledgebase/article/details/132716835