Header Only Library
Websocket Server
How to use Websocket server class
References
#include "ip.hpp"
#include "ip/websocket/wsserver.hpp"
Syntax
namespace internetprotocol
class ws_server_c
Example Code
#include <iostream>
#include "ip.hpp"
using namespace internetprotocol;
int main()
{
ws_server_c net;
net.on_error = [&](const asio::error_code &ec) {
std::cout << ec.message() << std::endl;
};
net.on_client_accepted = [&](const std::shared_ptr<ws_remote_c> &client) {
std::cout << "Client connected" << std::endl;
client->on_error = [&](const asio::error_code &ec) {
std::cout << ec.message() << std::endl;
};
client->on_close = [&](const uint16_t code, const std::string &reason) {
std::cout << code << " -> " << reason << std::endl;
};
client->on_message_received = [&](const std::vector<uint8_t> &buffer, bool is_binary) {
std::cout << "Message received: " << buffer_to_string(buffer) << std::endl;
};
};
net.open();
std::string input;
while (std::getline(std::cin, input)) {
if (input == "quit") {
net.close();
break;
}
for (const auto &client : net.clients()) {
client->write(input, {}, [](const asio::error_code &ec, const size_t bytes_sent) {
// Check if message has been sent
});
}
}
join_threads();
return 0;
}
Variables
Backlog
- Sets the maximum number of simultaneous client connections the server will accept in queue.
int backlog
Functions
Is Open
- Return true if socket is open.
bool is_open() const
Local Endpoint
- Get the local endpoint of the socket. Use this function only after open connection.
tcp::endpoint local_endpoint() const
Clients
- Gets a constant reference to the set of clients connected to the server.
const std::set<std::shared_ptr<tcp_remote_c>> &clients() const
Get Error Code
- Return a const ref of the latest error code returned by asio.
const asio::error_code &get_error_code() const
Open
- Open connection
- Return false if socket is already open or any error occurs
- Event
on_error
is triggered if any error occurs
bool open(const server_bind_options_t &bind_opts = { "", 8080, v4, true }))
Close
- Disconnect all clients and close connection
void close()
Events
Events
On Listening
- This event will be triggered when socket start to listening.
std::function<void()> on_listening
On Client Accepted
- This event will be triggered when new client connect.
std::function<void(const std::shared_ptr<ws_remote_c> &)> on_client_acceptedpted
On Close
- Event triggered when socket and acceptor is closed
std::function<void()> on_close
On Error
- Event triggered if any error occur during async process
const asio::error_code &
: if error occur, error code will be different from 0
std::function<void(const asio::error_code &)> on_error