NAP
Public Member Functions | Protected Member Functions | Protected Attributes | List of all members
WebSocketServerEndPointSetup< config > Class Template Reference

#include <websocketconnection.h>

Public Member Functions

 ~WebSocketServerEndPointSetup () override
 
bool init (utility::ErrorState &errorState) override
 
bool start (nap::utility::ErrorState &error) override
 
bool isOpen () const override
 
void stop () override
 
bool send (const WebSocketConnection &connection, const std::string &message, EWebSocketOPCode code, nap::utility::ErrorState &error) override
 
bool send (const WebSocketConnection &connection, void const *payload, int length, EWebSocketOPCode code, nap::utility::ErrorState &error) override
 
bool broadcast (const std::string &message, EWebSocketOPCode code, nap::utility::ErrorState &error) override
 
bool broadcast (void const *payload, int length, EWebSocketOPCode code, nap::utility::ErrorState &error) override
 
std::string getHostName (const WebSocketConnection &connection) override
 
void getHostNames (std::vector< std::string > &outHosts) override
 
int getConnectionCount () override
 
bool acceptsNewConnections () override
 

Protected Member Functions

void registerListener (IWebSocketServer &server) override
 
void unregisterListener (IWebSocketServer &server) override
 
void run ()
 
void onConnectionOpened (wspp::ConnectionHandle connection)
 
void onConnectionClosed (wspp::ConnectionHandle connection)
 
void onConnectionFailed (wspp::ConnectionHandle connection)
 
void onMessageReceived (wspp::ConnectionHandle con, wspp::MessagePtr msg)
 
void onHTTP (wspp::ConnectionHandle con)
 
bool onValidate (wspp::ConnectionHandle con)
 
bool onPing (wspp::ConnectionHandle con, std::string msg)
 
bool disconnect (nap::utility::ErrorState &error)
 

Protected Attributes

bool mRunning = false
 If the server is accepting and managing client connections. More...
 
std::mutex mConnectionMutex
 Ensures connections are added / removed safely. More...
 
std::unordered_set< WebSocketTicketHashmClientHashes
 Accepted client ticket hashes. More...
 
websocketpp::server< config > mEndPoint
 The websocketpp server end-point. More...
 
uint32 mLogLevel = 0
 Converted library log level. More...
 
uint32 mAccessLogLevel = 0
 Log client / server connection data. More...
 
std::future< void > mServerTask
 The background server thread. More...
 
std::vector< wspp::ConnectionHandlemConnections
 List of all low level connections. More...
 
std::mutex mListenerMutex
 Ensures registration is thread safe. More...
 
std::vector< IWebSocketServer * > mListeners
 All registered web socket servers. More...
 

Description

template<typename config>
class nap::WebSocketServerEndPointSetup< config >

Web socket server endpoint implementation using a specific configuration. Manages all client connections, where the config is the websocketpp (secured / unsecured) end-point configuration type.

On start the web-socket endpoint starts listening to connection requests, updates and messages on a background thread. The endpoint is a device that can be started and stopped. When stopped all active client-server connections are closed. This occurs when file changes are detected and the content of the application is hot-reloaded. A call to open is non blocking. Messages are forwarded to all clients that implement the nap::IWebSocketClient interface. Clients must register themselves to the various signals to receive connection updates and messages. Note that depending on your operating system you might have to run the application as administrator to open a web-socket.

By default the server accepts all client connection requests. Change the 'AccessMode' property to 'Ticket' or 'Reserved' to add a client identification scheme. When set to 'Ticket' the server accepts every client connection with a ticket. When set to 'Reserved' the server only accepts the connection if it has a matching ticket. Tickets that are accepted by the server can be added to the 'Clients' property.

A good analogy is that of attending a concert. When the mode is set to 'Everyone' you don't need to pick up a ticket in order to enter the venue. You can just walk in. When the mode is set to 'Ticket' you need to buy a ticket and show it at the front door. Everyone can buy a ticket. When the mode is set to 'Reserved' you need to be on the guest list. If you're not on the guest-list you are not allowed to buy a ticket, let alone enter the venue.

For both modes (Ticket and Reserved) you need to acquire a ticket by sending a HTTP 'POST' request to the server. The body of the post should contain a JSON formatted string that contains 2 fields: 'user' and 'pass'. Both fields are always required. For example:

{
"user": "napuser"
"pass": "letmein"
}

The server generates a new ticket based on the provided information and sends it back to the client that made the request. The received ticket should be specified as the first SUB-PROTOCOL argument when creating the web-socket. The server extracts the ticket on authorization and checks if it is valid. After validation the connection is accepted or rejected. Note that when the mode is set to 'Everyone' the server will not serve any tickets and you should not provide the system with one when connecting to the server. In that case: connect without specifying a sub-protocol.

The reason for having the 'Ticket' validation mode (next to 'Reserved') is to prevent any user or bot to log in automatically but allow 'interested' users free access. Every nap::WebSocketClient can make it's own ticket and therefore doesn't require the http post request. The NAP client still needs to have a correct username and password if required by the server.

Constructor & Destructor Documentation

◆ ~WebSocketServerEndPointSetup()

Member Function Documentation

◆ acceptsNewConnections()

bool acceptsNewConnections
override
Returns
if the server end point accepts new connections

◆ broadcast() [1/2]

bool broadcast ( const std::string &  message,
EWebSocketOPCode  code,
nap::utility::ErrorState error 
)
override

Sends a message to a all connected clients.

Parameters
messagethe message to send
codemessage type
errorcontains the error if sending fails

◆ broadcast() [2/2]

bool broadcast ( void const *  payload,
int  length,
EWebSocketOPCode  code,
nap::utility::ErrorState error 
)
override

Broadcasts a message to all connected clients using the given payload and opcode.

Parameters
payloadthe message buffer
lengthsize of the buffer in bytes
codemessage type
errorcontains the error if sending fails
Returns
if message was send successfully

◆ disconnect()

bool disconnect ( nap::utility::ErrorState error)
protected

Closes all active client connections.

◆ getConnectionCount()

int getConnectionCount
override
Returns
total number of active connections

◆ getHostName()

std::string getHostName ( const WebSocketConnection connection)
override
Returns
a client connection host-name, empty string if the connection is not managed by this end-point.

◆ getHostNames()

void getHostNames ( std::vector< std::string > &  outHosts)
override

Returns a list of all currently connected client host-names.

Parameters
outHoststhe list of connected client host-names.

◆ init()

bool init ( utility::ErrorState errorState)
override

Initializes the server endpoint.

Parameters
errorStatecontains the error when initialization fails
Returns
if initialization succeeded

◆ isOpen()

bool isOpen
override
Returns
if the current end point is open and running

◆ onConnectionClosed()

void onConnectionClosed ( wspp::ConnectionHandle  connection)
protected

Called when a client collection is closed

◆ onConnectionFailed()

void onConnectionFailed ( wspp::ConnectionHandle  connection)
protected

Called on a failed client connection attempt.

◆ onConnectionOpened()

void onConnectionOpened ( wspp::ConnectionHandle  connection)
protected

Called when a new client connection opened.

◆ onHTTP()

void onHTTP ( wspp::ConnectionHandle  con)
protected

Called when a http request is made. Creates and serves a ticket based on the current Access Mode.

◆ onMessageReceived()

void onMessageReceived ( wspp::ConnectionHandle  con,
wspp::MessagePtr  msg 
)
protected

Called when a new client message is received.

◆ onPing()

bool onPing ( wspp::ConnectionHandle  con,
std::string  msg 
)
protected

Called when the server receives a ping message. Automatically pongs back.

◆ onValidate()

bool onValidate ( wspp::ConnectionHandle  con)
protected

Validates the incoming connection. For now all connections are accepted.

◆ registerListener()

void registerListener ( IWebSocketServer server)
overrideprotected

Register a server for this endpoint so that it receives notifications from the endpoint.

Parameters
serverthe server to register

◆ run()

void run
protected

Runs the end point in a background thread until stopped.

◆ send() [1/2]

bool send ( const WebSocketConnection connection,
const std::string &  message,
EWebSocketOPCode  code,
nap::utility::ErrorState error 
)
override

Sends a message to a client.

Parameters
connectionthe client connection
messagethe message to send
codemessage type
errorcontains the error if sending fails
Returns
if message was send successfully

◆ send() [2/2]

bool send ( const WebSocketConnection connection,
void const *  payload,
int  length,
EWebSocketOPCode  code,
nap::utility::ErrorState error 
)
override

Sends a message to a client using the given payload and opcode.

Parameters
connectionthe client connection
payloadthe message buffer
lengthsize of the buffer in bytes
codemessage type
errorcontains the error if sending fails
Returns
if message was send successfully

◆ start()

bool start ( nap::utility::ErrorState error)
override

Opens the port and starts listening to connection requests, connection updates and messages in a background thread.

Parameters
errorcontains the error if the operation failed.
Returns
if the endpoint started successfully.

◆ stop()

void stop
override

Stops the end-point from running, all active connections are closed.

◆ unregisterListener()

void unregisterListener ( IWebSocketServer server)
overrideprotected

Unregister a server for this endpoint so that it stops receiving notifications from the endpoint.

Parameters
serverthe server to unregister

Member Data Documentation

◆ mAccessLogLevel

uint32 mAccessLogLevel = 0
protected

Log client / server connection data.

◆ mClientHashes

std::unordered_set<WebSocketTicketHash> mClientHashes
protected

Accepted client ticket hashes.

◆ mConnectionMutex

std::mutex mConnectionMutex
protected

Ensures connections are added / removed safely.

◆ mConnections

std::vector<wspp::ConnectionHandle> mConnections
protected

List of all low level connections.

◆ mEndPoint

websocketpp::server<config> mEndPoint
protected

The websocketpp server end-point.

◆ mListenerMutex

std::mutex mListenerMutex
protected

Ensures registration is thread safe.

◆ mListeners

std::vector<IWebSocketServer*> mListeners
protected

All registered web socket servers.

◆ mLogLevel

uint32 mLogLevel = 0
protected

Converted library log level.

◆ mRunning

bool mRunning = false
protected

If the server is accepting and managing client connections.

◆ mServerTask

std::future<void> mServerTask
protected

The background server thread.