Skip to content

Build software based on WebSocket++

muhler edited this page Nov 23, 2011 · 1 revision

Building a program using WebSocket++ has two parts:

Part I: Implement a connection handler

This is done by subclassing websocketpp::connection_handler. Each websocket connection is attached to a connection handler. The handler implements the following methods:

validate()

Called after the client handshake is received but before the connection is accepted. Allows cookie authentication, origin checking, subprotocol negotiation, etc.

connect()

Called when the connection has been established and writes are allowed.

disconnect()

Called when the connection has been disconnected.

message() (text and binary variants)

Called when a new websocket message is received.

websocket session API

The handler has access to the following websocket session API methods:

get_header()

returns the value of an HTTP header sent by the client during the handshake

get_request()

returns the resource requested by the client in the handshake

set_handler()

pass responsibility for this connection to another connection handler

set_http_error()

reject the connection with a specific HTTP error

add_header()

adds an HTTP header to the server handshake

set_subprotocol()

selects a subprotocol for the connection

send() (text and binary variants)

send a websocket message

ping()

send a ping

Part II: Start Asio’s event loop with a TCP endpoint and your connection handler

There are two example programs in the examples directory that demonstrate this use pattern. One is a trivial stateless echo server, the other is a simple web based chat client. Both include example javascript clients. The echo server is suitable for use with automated testing suites such as the Autobahn test suite.

By default, a single connection handler object is used for all connections. If needs require, that default handler can either store per-connection state itself or create new handlers and pass off responsibility for the connection to them.