CppServer  1.0.4.0
C++ Server Library
ws_chat_client.cpp

WebSocket chat client example

#include "asio_service.h"
#include "threads/thread.h"
#include <atomic>
#include <iostream>
class ChatClient : public CppServer::WS::WSClient
{
public:
void DisconnectAndStop()
{
_stop = true;
CloseAsync(1000);
while (IsConnected())
CppCommon::Thread::Yield();
}
protected:
{
request.SetBegin("GET", "/");
request.SetHeader("Host", "localhost");
request.SetHeader("Origin", "http://localhost");
request.SetHeader("Upgrade", "websocket");
request.SetHeader("Connection", "Upgrade");
request.SetHeader("Sec-WebSocket-Key", CppCommon::Encoding::Base64Encode(ws_nonce()));
request.SetHeader("Sec-WebSocket-Protocol", "chat, superchat");
request.SetHeader("Sec-WebSocket-Version", "13");
}
void onWSConnected(const CppServer::HTTP::HTTPResponse& response) override
{
std::cout << "Chat WebSocket client connected a new session with Id " << id() << std::endl;
}
void onWSDisconnected() override
{
std::cout << "Chat WebSocket client disconnected a session with Id " << id() << std::endl;
}
void onWSReceived(const void* buffer, size_t size) override
{
std::cout << "Incoming: " << std::string((const char*)buffer, size) << std::endl;
}
void onDisconnected() override
{
// Wait for a while...
CppCommon::Thread::Sleep(1000);
// Try to connect again
if (!_stop)
}
void onError(int error, const std::string& category, const std::string& message) override
{
std::cout << "Chat WebSocket 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)
{
// WebSocket server address
std::string address = "127.0.0.1";
if (argc > 1)
address = argv[1];
// WebSocket server port
int port = 8080;
if (argc > 2)
port = std::atoi(argv[2]);
std::cout << "WebSocket server address: " << address << std::endl;
std::cout << "WebSocket server port: " << port << std::endl;
std::cout << std::endl;
// Create a new Asio service
auto service = std::make_shared<AsioService>();
// Start the Asio service
std::cout << "Asio service starting...";
service->Start();
std::cout << "Done!" << std::endl;
// Create a new WebSocket chat client
auto client = std::make_shared<ChatClient>(service, address, port);
// Connect the client
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;
// Perform text input
std::string line;
while (getline(std::cin, line))
{
if (line.empty())
break;
// Reconnect the client
if (line == "!")
{
std::cout << "Client reconnecting...";
client->IsConnected() ? client->ReconnectAsync() : client->ConnectAsync();
std::cout << "Done!" << std::endl;
continue;
}
// Send the entered text to the chat server
client->SendTextAsync(line);
}
// Disconnect the client
std::cout << "Client disconnecting...";
client->DisconnectAndStop();
std::cout << "Done!" << std::endl;
// Stop the Asio service
std::cout << "Asio service stopping...";
service->Stop();
std::cout << "Done!" << std::endl;
return 0;
}
bool IsConnected() const noexcept
Is the client connected?
Definition: tcp_client.h:101
virtual void onError(int error, const std::string &category, const std::string &message)
Handle error notification.
Definition: tcp_client.h:320
const CppCommon::UUID & id() const noexcept
Get the client Id.
Definition: tcp_client.h:60
HTTPRequest & SetBegin(std::string_view method, std::string_view url, std::string_view protocol="HTTP/1.1")
Set the HTTP request begin with a given method, URL and protocol.
HTTPRequest & SetHeader(std::string_view key, std::string_view value)
Set the HTTP request header.
WebSocket client.
Definition: ws_client.h:27
virtual bool CloseAsync()
Definition: ws_client.h:47
bool ConnectAsync() override
Connect the client (asynchronous)
Definition: ws_client.cpp:26
WSClient(const WSClient &)=delete
void onDisconnected() override
Handle client disconnected notification.
Definition: ws_client.cpp:56
std::string_view ws_nonce() const noexcept
Get the WebSocket random nonce.
Definition: ws.h:54
virtual void onWSConnecting(HTTP::HTTPRequest &request)
Handle WebSocket client connecting notification.
Definition: ws.h:107
virtual void onWSReceived(const void *buffer, size_t size)
Handle WebSocket received notification.
Definition: ws.h:139
virtual void onWSConnected(const HTTP::HTTPResponse &response)
Handle WebSocket client connected notification.
Definition: ws.h:112
virtual void onWSDisconnected()
Handle WebSocket client disconnected notification.
Definition: ws.h:132
WebSocket client definition.