Header Only Library
TCP Server
How to use TCP server class
References
#include "ip.hpp"
#include "ip/tcp/tcpserver.hpp"
Syntax
namespace internetprotocol
class tcp_server_c
Example code
#include <iostream>
#include "ip.hpp"
using namespace InternetProtocol;
int main()
{
tcp_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<tcp_remote_c> &client) {
client->on_message_received = [&, client](const std::vector<uint8_t> &buffer, const size_t bytes_recvd) {
std::cout << client->local_endpoint().port() << " -> " << buffer_to_string(buffer) << std::endl;
};
client->on_close = [&, client]() {
std::cout << "client logout" << std::endl;
};
};
net.bind();
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, size_t bytes_sent) {
// Check if message has been sent
});
}
}
join_threads();
return 0;
}
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
- Opens the TCP server and starts listening for incoming connections.
- 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
- Close the underlying socket and stop listening for data on it. 'on_close' event will be triggered.
void close()
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<tcp_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