Write on multiply connections

This question is sequel to my first question about simple example of bidirectional connection and server/client implementation.
I’ve tried to add write_loop to WebScoketSession class based on this example, but it(as i’ve expected) doesn’t work.

After that I’ve add little broadcast functional to server class, that will notify all previously connected users about new connection, but it fails with string iterator error, what i cant understand at all.
Also i would like to know how to set event for closing connections, if it generaly possible or better than my current implementation based on destructor call, that redirects it to the server with tcp::endpoint instance.

Server side:

namespace asio = boost::asio;
namespace beast = boost::beast;
namespace websocket = beast::websocket;
using tcp = asio::ip::tcp;
using json = nlohmann::json;

class WebSocketSession;

class WebSocketServer {
public:
    WebSocketServer(asio::io_context& ioc, tcp::endpoint endpoint);
    void remove_connection(tcp::endpoint peer);
private:
    void do_accept();
    void on_accept(beast::error_code ec, tcp::socket socket);
private:
    std::mutex connections_mutex_;
    tcp::acceptor acceptor_;
    std::unordered_map<tcp::endpoint, std::shared_ptr<WebSocketSession>> connections;
};

class WebSocketSession : public std::enable_shared_from_this<WebSocketSession> {
public:
    WebSocketSession(tcp::socket socket, WebSocketServer* owner) :
        ws_(std::move(socket)),
        peer_(ws_.next_layer().remote_endpoint()),
        owner(owner)
    {};

    void run() {
        ws_.async_accept(beast::bind_front_handler(&WebSocketSession::on_accept, shared_from_this()));
    }

    ~WebSocketSession() { 
        try {
            if (owner == nullptr)throw std::exception("owner is absent for this connection");
            owner->remove_connection(peer_);
        }
        catch (std::exception const& e) {
            std::cerr << "Error on closing connection: " << e.what() << "n";
        }
        std::cerr << "Session " << peer_ << " closed" << std::endl;
    }

    void send(json data) {
        _tx.emplace_back(std::move(data));
        asio::post(
            ws_.get_executor(),
            [=] {
                if (_tx.size() == 0)return;
                do_write_loop();
            }
        );
    }

private:
    void on_accept(beast::error_code ec) {
        std::cerr << "Accept: " << ec.message() << " for " << peer_ << std::endl;

        if (!ec) {
            do_read_loop();
        }
    }

    void do_write_loop() {
        if (_tx.size() == 0)return;
        ws_.async_write(
            asio::buffer(_tx.front().dump()),
            beast::bind_front_handler(&WebSocketSession::on_write, shared_from_this())
        );
    }

    void on_write(beast::error_code ec, size_t n) {
        _tx.pop_back();
        if (ec) {
            if (ec == websocket::error::closed) {
                return;
            }
            std::cerr << "Write error: " << ec.message() << std::endl;
            return;
        }
    }

    void do_read_loop() {
        ws_.async_read(
            buffer_,
            beast::bind_front_handler(&WebSocketSession::on_read, shared_from_this())
        );
    }

    void on_read(beast::error_code ec, size_t n) {
        if (ec) {
            if (ec == websocket::error::closed) {
                return;
            }
            std::cerr << "Read error: " << ec.message() << std::endl;
            return;
        }

        try {
            response_.clear();

            auto it = buffers_begin(buffer_.data());
            json msg = json::parse(it, it + n);
            buffer_.consume(n);

            if (msg.contains("echo"))
                response_ = json{ {"type", "response"}, {"original", std::move(msg)} }.dump();

            if (response_.empty()) {
                do_read_loop();
            }
            else {
                ws_.text(true);
                ws_.async_write(
                    asio::buffer(response_),
                    beast::bind_front_handler(&WebSocketSession::on_write_read_loop, shared_from_this())
                );
            }
        }
        catch (std::exception const& e) {
            std::cerr << "Processing error: " << e.what() << std::endl;
        }
    }

    void on_write_read_loop(beast::error_code ec, size_t n) {
        std::cerr << "Write: " << n << " bytes (" << ec.message() << ")" << std::endl;
        if (!ec) {
            do_read_loop();
        }
    }

    WebSocketServer* owner;

    std::list<json> _tx;

    websocket::stream<tcp::socket> ws_;
    tcp::endpoint peer_;

    beast::flat_buffer buffer_;
    std::string response_;
};

//
WebSocketServer::WebSocketServer(asio::io_context& ioc, tcp::endpoint endpoint) : acceptor_(ioc, endpoint) { do_accept(); }

void WebSocketServer::do_accept() { acceptor_.async_accept(beast::bind_front_handler(&WebSocketServer::on_accept, this)); }

void WebSocketServer::on_accept(beast::error_code ec, tcp::socket socket) {
    tcp::endpoint last_connection;
    if (ec) {
        std::cerr << "Accept error: " << ec.message() << std::endl;
    }
    else {
        last_connection = socket.remote_endpoint();
        const auto insertedPair = connections.insert({ 
            last_connection,
            std::make_shared<WebSocketSession>(std::move(socket), this) 
        }).first;
        insertedPair->second->run();
    }

    do_accept();
    
    //notify all except last connected user
    for (const auto& pair : connections) {
        if (pair.first == last_connection)continue;
        pair.second->send({ "Mesage", "New user on server" });
    }
}
void WebSocketServer::remove_connection(tcp::endpoint peer) {
    std::lock_guard<std::mutex> lock(connections_mutex_);
    connections.erase(peer);
}
//

int main() {
    try {
        asio::io_context ioc;
        tcp::endpoint endpoint(tcp::v4(), 9002);
        WebSocketServer server(ioc, endpoint);
        ioc.run();
        std::cout << "Server is running:n";
    }
    catch (std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật