v1.3.0.0
WebSocket

Description

Implementation of the WebSocket Web API

Since
1.3

WebSockets is a web technology providing full-duplex communications channels over a single TCP connection.

The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.

This implementation replicates all of the standard interface and most of the behavior and options, except as noted below. There are also many additions, some of which replicate the Node-js websockets/ws implementation.

Major differences vs. typical standard implementations:

  • The socket is not automatically opened when a WebSocket instance is created. You must explicitly call the open() method to initiate a connection. Do this after connecting all your event listeners/handlers.
  • WebSocket doesn't throw any exceptions. All errors are reported in the error event.
  • HTTP redirects are not supported (WebSocket will report an "Unhandled http status code: 301" error). This includes redirects from ws: to wss: protocol URLs.
  • The binaryType property only supports "arraybuffer", which is the default. (Note that a new type "fragments" is available, similar to the Node-js version).
  • A connected WebSocket instance automatically responds to all "ping" messages from the server.
  • No websocket protocol "extensions" are supported, notably per-message-deflate (compression of individual messages). (Note that extensions are not the same as "sub-protocols" describing the message exchange format, such as "json" or "xml".)

Example

Exchange messages with an "echo" WebSockets server.

// Create instance and specify the server URL. This public "echo" service sends back whatever we send it.
const ws = new WebSocket('wss://websocket-echo.com/');
// The "open" event is triggered once a connection to the server is established.
ws.onopen = function() {
console.log('WebSocket client connected at', Date.now());
// Send a text message with the current timestamp.
ws.send(Date.now());
};
// The "message" event is triggered when a message arrives from the server.
// In this case it will be the echo reply to the message we sent in the "open" event handler above.
ws.onmessage = function(messageEvent) {
// Prints the time difference between current time and the time we sent to the echo server.
console.log(`Round-trip time: ${Date.now() - messageEvent.data} ms`);
// Once we're done with the socket, close it. The code and reason are optional.
ws.close(1000, "Finished!");
};
// The "close" event happens when the socket disconnects.
ws.onclose = function(closeEvent) {
console.log(`Disconnected at ${Date.now()} with code: ${closeEvent.code} reason: ${closeEvent.reason || "[none given]"}`);
// This is a good place to delete the WebSocket instance __if we're not going to use it again__.
ws = null;
};
// Error handler. The argument would be an instance of a generic `Error` type. Just connect to console output for this example.
ws.onerror = console.error;
// Start the connection
ws.open();
Date prototype extension methods
Implementation of the WebSocket Web API
Definition: WebSocket.h:128

Member Objects

struct  Options
 

Public Types

enum  ReadyState
 
enum  CloseCode
 

Properties

string binaryType
 
int bufferedAmount
 
qint16 closeCode
 
string closeReason
 
Socket::SocketError errorCode
 
string errorString
 
string extensions
 
Object headers
 
string localAddress
 
uint localPort
 
string peerAddress
 
string peerName
 
uint peerPort
 
string protocol
 
WebSocket::ReadyState readyState
 
Array< string > requestedProtocols
 
string url
 
int version
 

Public Member Functions

 WebSocket (Options &options=Options())
 
 WebSocket (string &url, Options &options=Options())
 
 WebSocket (string &url, Array< string > &protocols, Options &options=Options())
 
 WebSocket (string &url, string &protocol, Options &options=Options())
 
void abort ()
 
void close (qint16 closeCode=CloseCode::NormalCloseCode, string &reason="")
 
void open (Function callback=undefined)
 
void ping (ArrayBuffer &payload=ArrayBuffer())
 
int send (any data,< object|boolean > options=false)
 
int sendText (any message)
 
int sendBinary (ArrayBuffer &bytes)
 
void setOptions (Options &options)
 
void terminate ()
 
Events
See also
Event Handling for general information about connecting listeners to events.
void bytesWritten (int bytes)
 
void closed (Object &closeEvent)
 
void error (Error error)
 
void opened ()
 
void message (Object &messageEvent)
 
void readyStateChanged (WebSocket::ReadyState newState)
 
void pong (quint64 elapsedTime, ArrayBuffer &payload)
 

Class Documentation

◆ WebSocket::Options

struct WebSocket::Options

Options object for use in WebSocket constructor or setOptions() method. All properties are optional.

Class Members
int protocolVersion WebSockets protocol version to use. Supported versions are: 0, 4, 5, 6, 7, 8, and 13 (default). Note that the protocol version must be set before the initial call to open().
string origin Value for the Origin or Sec-WebSocket-Origin header (depending on the protocolVersion). Note that the origin must be set before the initial call to open(). To change the origin afterwards, re-create the WebSocket instance entirely.
< string|string[] > protocols A single string or an array of strings representing the sub-protocol(s) that the client would like to use, in order of preference. This is an alternative to setting the protocol(s) in the WebSocket constructor, and will override any specified there.
string binaryType A string indicating the type of binary data being transmitted by the connection. This should be one of "arraybuffer" or "fragments". See WebSocket::binaryType property for details.
object headers Extra headers to include with the WebSocket requests. Object of { header_name: "header_value" } pairs. Sets the WebSocket::headers property.
int maxIncomingMessageSize Sets the maximum allowed size of an incoming websocket message. If an incoming message exceeds this limit, the peer gets disconnected.
int maxIncomingFrameSize Sets the maximum allowed size of an incoming websocket frame. If an incoming frame exceeds this limit, the peer gets disconnected.
int maxOutgoingFrameSize Sets the maximum size of an outgoing websocket frame. Default is 512KB.
int maxPayload The maximum allowed message size in bytes. This is the same as setting maxIncomingMessageSize, maxIncomingFrameSize, and maxOutgoingFrameSize properties all to the same value. If this property is present, the other 3 are ignored.
int handshakeTimeout Timeout for the initial server connection, in milliseconds.
int timeout Alias for handshakeTimeout. Timeout for the initial server connection, in milliseconds.

Member Enumeration Documentation

◆ ReadyState

enum ReadyState

Values for the readyState read-only property.

Enumerator
CONNECTING 

(0) Socket has been created but the connection is not yet open.

OPEN 

(1) The connection is open and ready to communicate.

CLOSING 

(2) The connection is in the process of closing.

CLOSED 

(3) The connection is closed or couldn't be opened.

◆ CloseCode

enum CloseCode

The close codes supported by WebSockets V13.

Enumerator
NormalCloseCode 

(1000) Normal closure.

GoingAwayCloseCode 

(1001) Going away.

ProtocolErrorCloseCode 

(1002) Protocol error.

DatatypeNotSupportedCloseCode 

(1003) Unsupported data.

Reserved1004CloseCode 

(1004) Reserved.

MissingStatusCodeCloseCode 

(1005) No status received.

AbnormalDisconnectionCloseCode 

(1006) Abnormal closure.

WrongDatatypeCloseCode 

(1007) Invalid frame payload data.

PolicyViolatedCloseCode 

(1008) Policy violation.

TooMuchDataCloseCode 

(1009) Message too big.

MissingExtensionCloseCode 

(1010) Mandatory extension missing.

BadOperationCloseCode 

(1011) Internal server error.

TlsHandshakeFailedCloseCode 

(1015) TLS handshake failed.

Constructor & Destructor Documentation

◆ WebSocket() [1/4]

WebSocket ( Options options = Options())
explicit

Creates a new WebSocket instance with no URL. Further options may be specified in the options argument.

The url property must be set before trying to open a connection with this instance.

See also
url, Options, setOptions

◆ WebSocket() [2/4]

WebSocket ( string &  url,
Options options = Options() 
)
explicit

Creates a new WebSocket instance with the given server URL. Further options may be specified in the options argument.

See also
url, Options, setOptions()

◆ WebSocket() [3/4]

WebSocket ( string &  url,
Array< string > &  protocols,
Options options = Options() 
)
explicit

Creates a new WebSocket instance with the given server URL and an array of sub-protocol names that the client would like to use, in order of preference. Further options may be specified in the options argument.

See also
url, requestedProtocols, protocol, Options, setOptions()

◆ WebSocket() [4/4]

WebSocket ( string &  url,
string &  protocol,
Options options = Options() 
)
explicit

Creates a new WebSocket instance with the given server URL and a single sub-protocol name. Further options may be specified in the options argument.

See also
url, requestedProtocols, protocol, Options, setOptions()

Property Documentation

◆ binaryType

string binaryType
readwrite

A string indicating the type of binary data being transmitted by the connection.

This should be one of "arraybuffer" or "fragments". Defaults to "arraybuffer".

Type "fragments" will emit the array of fragments as received from the sender, without copyfull concatenation, is useful for the performance of binary protocols transferring large messages with multiple fragments. The message() event's isLast property will be false for all fragments of a message except the final one.

◆ bufferedAmount

int bufferedAmount
read

The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.

◆ closeCode

qint16 closeCode
read

Returns the code indicating why the socket was closed.

◆ closeReason

string closeReason
read

Returns the reason why the socket was closed.

◆ errorCode

Socket::SocketError errorCode
read

Returns the type of error that last occurred, if any, or Socket.UnknownSocketError if no error has been raised.

See also
errorString

◆ errorString

string errorString
read

Contains a description of the last error that occurred. When no error occurred, this string is empty.

See also
errorCode

◆ extensions

string extensions
read

WS Extensions are not supported. This read-only property always returns an empty string.

◆ headers

Object headers
readwrite

Extra headers to include with the WebSocket requests. Object of `{ header_name: "header_value" } pairs.
Note that setting the headers on an open (connected) socket will not have any effect until the connection is closed and re-opened.

◆ localAddress

string localAddress
read

Returns the local IP address of this socket.

◆ localPort

uint localPort
read

Returns the local IP port of this socket.

◆ peerAddress

string peerAddress
read

Returns the peered server IP address.

◆ peerName

string peerName
read

Returns the peered server host name, if it can be resolved, or the IP address otherwise.

◆ peerPort

uint peerPort
read

Returns the peered server IP port.

◆ protocol

string protocol
read

The WebSocket subprotocol that has been negotiated with the server.

◆ readyState

WebSocket::ReadyState readyState
read

Status of the WebSocket.

The state can have the following values:

See also
readyStateChanged()

◆ requestedProtocols

Array<string> requestedProtocols
readwrite

The list of WebSocket subprotocols to send in the WebSocket handshake.

◆ url

string url
readwrite

Server URL to connect to. The URL must have one of 2 protocols: ws:// or wss://. When not supplied, then ws:// is used. If setting this property while a connection is already open then the current connection will first be closed, then re-opened with the new URL.

◆ version

int version
read

Returns the protocol version the socket is currently using. Read-only. Returns -1 if version is unknown for some reason. The desired protocol version can be set with WebSocket::Options either in the constructor or with setOptions() method, before the initial call to open().

Member Function Documentation

◆ abort()

void abort ( )

Immediately terminate any open connection. As opposed to close(), this method doesn't attempt to process any pending data.

See also
close()

◆ close()

void close ( qint16  closeCode = CloseCode::NormalCloseCode,
string &  reason = "" 
)

Gracefully closes the server connection by initiating a closing handshake. Any pending data is flushed before the socket is closed, if possible.

Parameters
closeCodeOptional code to indicate reason for closure. Typically one of the standard protocol codes, as enumerated by WebSocket.CloseCode. Default is 1000, or "normal."
reasonOptional reason text for the closure. Default is an empty string.
See also
abort()

◆ open()

void open ( Function  callback = undefined)

Attempts to open a connection to the server.

An optional callback Function may be provided as the first argument, which will then be invoked upon a successful connection, as if it was a handler for the usual opened event. The callback handler is always removed after this connection attempt, even if it fails (errors are emitted in the error event as usual). Any successive calls to open() would need to specify the callback again.

◆ ping()

void ping ( ArrayBuffer payload = ArrayBuffer())

Send a "ping" to the connected server. The server should respond with a "pong" message.

Parameters
payloadOptional data to send with the ping. This will be returned by the server in the "pong" message. Default payload value is empty.
See also
pong() event

◆ send()

int send ( any  data,
< object|boolean >  options = false 
)

Sends a message to the server.

Parameters
data{ primitive | ArrayBuffer | TypedArray | DataView } The data to send.
options{ object | boolean } Optional object specifying additional sending options. If the argument is a boolean type, it is interpreted as the binary option described below.
  • binary {boolean} Specifies whether data should be sent as a binary or not. Default is auto-detected based on data type (any primitive convertible to a string vs. an ArrayBuffer/typed array/view).
Returns
The number of bytes written to the socket or -1 in case of error.
See also
sendText(), sendBinary()

◆ sendText()

int sendText ( any  message)

Sends message to the server as UTF-8 text. message values that are not already strings are coerced to strings. Returns the number of bytes written to the socket or -1 in case of error.

See also
send(), sendBinary()

◆ sendBinary()

int sendBinary ( ArrayBuffer bytes)

Sends the contents of bytes array buffer to the server. Returns the number of bytes written to the socket or -1 in case of error.

See also
send(), sendText()

◆ setOptions()

void setOptions ( Options options)

Sets options on this WebSocket instance.
Note that some options must be set before the socket is initially opened. And some options will not take effect until the next time the socket is opened.
The same options can be specified here as in the various constructor overloads. Any options not included in the options argument object are left unchanged.

◆ terminate()

void terminate ( )

Alias for abort() method.

◆ bytesWritten()

void bytesWritten ( int  bytes)

Emitted after data has been sent to the server (with send() method). The event listener argument is the number of bytes transferred.

This event has a corresponding onbytesWritten property to which a single event handler may be assigned.

See also
bufferedAmount

◆ closed()

void closed ( Object &  closeEvent)

Emitted when a connection is closed. An object with the following properties is passed as an argument to event handlers:

  • code {number} - Numeric value indicating the status code explaining why the connection has been closed. This could be one of the standard websocket close codes as enumerated by WebSocket::CloseCode.
  • reason {string} - May contain a textual explanation of the reason for the socket closure.
  • wasClean {boolean} - A flag indicating if the socket closure was expected/"clean" (true) or not (false).

This event has a corresponding onclose property to which a single event handler may be assigned (also aliased as onclosed).
When connecting to this event with on() or addEventListener() methods, the event name may be specified as either "close" or "closed".

◆ error()

void error ( Error  error)

Emitted when an error occurs. A standard Error type object is passed as an argument to event handlers.

  • message {string} - This standard property will contain text describing the error.
  • code {number} - Custom property indicating the corresponding error code. This should be one of the values enumerated by Socket.SocketError.

This event has a corresponding onerror property to which a single event handler may be assigned.

Note
If no listener is assigned to this event then errors will bubble up to the global level and will be reported & logged as an "engine instance" error.

◆ opened()

void opened ( )

Emitted when a connection is established. This event passes no arguments to the handler.

This event has a corresponding onopen property to which a single event handler may be assigned (also aliased as onopened).
When connecting to this event with on() or addEventListener() methods, the event name may be specified as either "open" or "opened".

◆ message()

void message ( Object &  messageEvent)

Emitted when a message is received. An object with the following properties is passed as an argument to event handlers:

  • data { String | ArrayBuffer } - The message content.
  • isBinary {boolean} - specifies whether the message in data is binary or not.
  • isLast {boolean} - Used when binaryType is set to "fragments". This will be false for all fragments of a message except the final one.

This event has a corresponding onmessage property to which a single event handler may be assigned.

◆ readyStateChanged()

void readyStateChanged ( WebSocket::ReadyState  newState)

This event is emitted when the readyState property changes.

Parameters
newState- the current state value.

This event has a corresponding onreadyStateChanged property to which a single event handler may be assigned.

See also
readyState, WebSocket.ReadyState

◆ pong()

void pong ( quint64  elapsedTime,
ArrayBuffer payload 
)

Emitted when a "pong" message is received from the current server. Two arguments are passed to event listeners:

Parameters
elapsedTime{number} - Round-trip time in milliseconds.
payload{ArrayBuffer} - Optional payload data that was sent with the original "ping" message.

This event has a corresponding onpong property to which a single event handler may be assigned.

See also
ping()