#include "asio_service.h"
#include "threads/thread.h"
#include <atomic>
#include <iostream>
{
public:
void DisconnectAndStop()
{
_stop = true;
CppCommon::Thread::Yield();
}
protected:
{
std::cout <<
"Chat TCP client connected a new session with Id " <<
id() << std::endl;
}
{
std::cout <<
"Chat TCP client disconnected a session with Id " <<
id() << std::endl;
CppCommon::Thread::Sleep(1000);
if (!_stop)
}
void onReceived(
const void* buffer,
size_t size)
override
{
std::cout << "Incoming: " << std::string((const char*)buffer, size) << std::endl;
}
void onError(
int error,
const std::string& category,
const std::string& message)
override
{
std::cout << "Chat TCP client caught an error with code " << error << " and category '" << category << "': " << message << std::endl;
}
private:
std::atomic<bool> _stop{false};
};
int main(int argc, char** argv)
{
std::string address = "127.0.0.1";
if (argc > 1)
address = argv[1];
int port = 1111;
if (argc > 2)
port = std::atoi(argv[2]);
std::cout << "TCP server address: " << address << std::endl;
std::cout << "TCP 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 client = std::make_shared<ChatClient>(service, address, port);
std::cout << "Client connecting...";
client->ConnectAsync();
std::cout << "Done!" << std::endl;
std::cout << "Press Enter to stop the client or '!' to reconnect the client..." << std::endl;
std::string line;
while (getline(std::cin, line))
{
if (line.empty())
break;
if (line == "!")
{
std::cout << "Client reconnecting...";
client->IsConnected() ? client->ReconnectAsync() : client->ConnectAsync();
std::cout << "Done!" << std::endl;
continue;
}
client->SendAsync(line);
}
std::cout << "Client disconnecting...";
client->DisconnectAndStop();
std::cout << "Done!" << std::endl;
std::cout << "Asio service stopping...";
service->Stop();
std::cout << "Done!" << std::endl;
return 0;
}
bool IsConnected() const noexcept
Is the client connected?
TCPClient(const std::shared_ptr< Service > &service, const std::string &address, int port)
Initialize TCP client with a given Asio service, server address and port number.
virtual void onReceived(const void *buffer, size_t size)
Handle buffer received notification.
virtual void onDisconnected()
Handle client disconnected notification.
virtual void onConnected()
Handle client connected notification.
virtual void onError(int error, const std::string &category, const std::string &message)
Handle error notification.
virtual bool ConnectAsync()
Connect the client (asynchronous)
virtual bool DisconnectAsync()
Disconnect the client (asynchronous)
const CppCommon::UUID & id() const noexcept
Get the client Id.