Boost :: Asio peer-to-peer udp chat

I am writing a peer-to-peer program (it should not have a server - this is the task) for text messaging. This is a very tiny chat. Just messages, nothing more. This is my first practice with Boost :: Asio, so I have some questions.

My chat should be peer-to-peer, as I said, and it must use the udp protocol. I think the best way is to use broadcast. And the first problem: how can I find out about new connections?

Another problem is sending a message: I send it to a broadcast address, and then it spreads to all computers on the local network. Correctly?

This code sends a message and receives it back. Like an echo. Correctly?

#include <iostream>
#include <boost/asio.hpp>
#include <boost/array.hpp>

int main()
{
    try 
    {
        namespace ip = boost::asio::ip;
        boost::asio::io_service io_service;

        ip::udp::socket socket(io_service,
            ip::udp::endpoint(ip::udp::v4(), 1555));
        socket.set_option(boost::asio::socket_base::broadcast(true));

        ip::udp::endpoint broadcast_endpoint(ip::address_v4::broadcast(), 1555);

        boost::array<char, 4> buffer1;
        socket.send_to(boost::asio::buffer(buffer1), broadcast_endpoint);

        ip::udp::endpoint sender_endpoint;

        boost::array<char, 4> buffer2;
        std::size_t bytes_transferred = 
            socket.receive_from(boost::asio::buffer(buffer2), sender_endpoint);

        std::cout << "got " << bytes_transferred << " bytes." << std::endl;
    }
    catch (std::exception &e)
    {
        std::cerr << e.what();
    }

    system("PAUSE");

    return 0;
}
+4

Source: https://habr.com/ru/post/1542071/


All Articles