currently I am writing a C++ Application for simulating some flying objects in the real world (like GIS).
All the visualization stuff should be made in one or more browser (1 server, X clients).
To connect the Sim APP with the Browser-Clients I decided to choose WebSocket (ws) for the data exchange.
I quickly landed on Boost.beast and looked at the examples… –> /example/websocket/server/async/websocket_server_async.cpp
This example works very well, but it’s not really what I need. It only responds to requests from a client.
I want the server to be able to send messages to a client (or all) independently.
Now I don’t know exactly what I need to change in the code to achieve this.
I have a listener that waits for connections from outside.
As soon as a connection needs to be established, a session is apparently created that is assigned to a socket.
Okay, I got it.
My first approach was to save all sessions in a std::vector in the listener class –> on_accept().
void
on_accept(beast::error_code ec, tcp::socket socket)
{
if(ec)
{
fail(ec, "accept");
}
else
{
// Create the session and run it
std::shared_ptr<session> oneSession = std::make_shared<session>(std::move(socket));
managedSessions.push_back(oneSession);
oneSession->run();
}
// Accept another connection
do_accept();
}
std::vector<std::shared_ptr<session>> managedSessions;
I adapted the on_read() function in the session class as a test to find out how I send “my own data” in the first place. That worked too:
void
on_read(
beast::error_code ec,
std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
// This indicates that the session was closed
if(ec == websocket::error::closed)
return;
if(ec)
return fail(ec, "read");
// Send the message
ws_.async_write(net::buffer(std::string("Data from the Server")),
beast::bind_front_handler(
&session::on_write,
shared_from_this()));
}
What I have is a sim loop where I calculate the movements of all entities and then of course have to report the changes to the clients.
It would be great if someone could give me a tip.
Thank you!!