#include "asio_service.h"
#include <iostream>
{
public:
protected:
{
}
void onReceived(
const asio::ip::udp::endpoint& endpoint,
const void* buffer,
size_t size)
override
{
std::string message((const char*)buffer, size);
std::cout << "Incoming: " << message << std::endl;
}
void onSent(
const asio::ip::udp::endpoint& endpoint,
size_t sent)
override
{
}
void onError(
int error,
const std::string& category,
const std::string& message)
override
{
std::cout << "Echo UDP server caught an error with code " << error << " and category '" << category << "': " << message << std::endl;
}
};
int main(int argc, char** argv)
{
int port = 3333;
if (argc > 1)
port = std::atoi(argv[1]);
std::cout << "UDP server port: " << port << std::endl;
std::cout << std::endl;
auto service = std::make_shared<AsioService>();
std::cout << "Asio service starting...";
service->Start();
std::cout << "Done!" << std::endl;
auto server = std::make_shared<EchoServer>(service, port);
std::cout << "Server starting...";
server->Start();
std::cout << "Done!" << std::endl;
std::cout << "Press Enter to stop the server or '!' to restart the server..." << std::endl;
std::string line;
while (getline(std::cin, line))
{
if (line.empty())
break;
if (line == "!")
{
std::cout << "Server restarting...";
server->Restart();
std::cout << "Done!" << std::endl;
continue;
}
}
std::cout << "Server stopping...";
server->Stop();
std::cout << "Done!" << std::endl;
std::cout << "Asio service stopping...";
service->Stop();
std::cout << "Done!" << std::endl;
return 0;
}
virtual void onStarted()
Handle server started notification.
virtual void ReceiveAsync()
Receive datagram from the client (asynchronous)
virtual void onError(int error, const std::string &category, const std::string &message)
Handle error notification.
virtual void onSent(const asio::ip::udp::endpoint &endpoint, size_t sent)
Handle datagram sent notification.
virtual bool SendAsync(const asio::ip::udp::endpoint &endpoint, const void *buffer, size_t size)
Send datagram into the given endpoint (asynchronous)
UDPServer(const std::shared_ptr< Service > &service, int port, InternetProtocol protocol=InternetProtocol::IPv4)
Initialize UDP server with a given Asio service and port number.
virtual void onReceived(const asio::ip::udp::endpoint &endpoint, const void *buffer, size_t size)
Handle datagram received notification.