Skip to content

Creating Applications using WebSocket++

zaphoyd edited this page Jan 17, 2012 · 7 revisions

A WebSocket++ application consists of two parts. An endpoint and a handler. The endpoint manages all aspects of the websocket protocol and accepts some configuration settings from you. The handler is an object passed to the endpoint that contains code to run for the various types of events (on_open, on_message, on_close, etc) that WebSocket connections generate.

Simplest example program:


#include <websocketpp.hpp> // this is a convenience header that includes only the basics
using websocketpp::server;

// This handler extends the generic server handler to echo back received messages.
struct echo_server_handler : public server::handler {
void on_message(connection_ptr connection,message_ptr msg) {
connection→send(msg→get_payload(),msg→get_opcode());
}
};

int main() {
// create a shared pointer to an echo_server_handler
server::handler_ptr echo_handler(new echo_server_handler());
// create a server endpoint and initialize with the new handler
server echo_endpoint(echo_handler);
// instruct the endpoint to listen for connections on port 9002
// this line will block until something within the endpoint event loop asks it to stop.
echo_endpoint.listen(9002);
return 0;
}

This code will start an echo server on port 9002. New connections will be accepted and every time a message is received by any of them the on_message member function of echo_handler will be run.