![]() |
v1.3.0.0
|
Implementation of the WebSocket Web API
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.
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.ws:
to wss:
protocol URLs.binaryType
property only supports "arraybuffer", which is the default. (Note that a new type "fragments" is available, similar to the Node-js version).WebSocket
instance automatically responds to all "ping" messages from the server.Exchange messages with an "echo" WebSockets server.
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 | |
| |
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) |
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. |
enum ReadyState |
Values for the readyState read-only property.
enum CloseCode |
The close codes supported by WebSockets V13.
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.
Creates a new WebSocket instance with the given server URL. Further options may be specified in the options
argument.
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.
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.
|
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.
|
read |
The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.
|
read |
Returns the code indicating why the socket was closed.
|
read |
Returns the reason why the socket was closed.
|
read |
Returns the type of error that last occurred, if any, or Socket.UnknownSocketError
if no error has been raised.
|
read |
Contains a description of the last error that occurred. When no error occurred, this string is empty.
|
read |
WS Extensions are not supported. This read-only property always returns an empty string.
|
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.
|
read |
Returns the local IP address of this socket.
|
read |
Returns the local IP port of this socket.
|
read |
Returns the peered server IP address.
|
read |
Returns the peered server host name, if it can be resolved, or the IP address otherwise.
|
read |
Returns the peered server IP port.
|
read |
The WebSocket subprotocol that has been negotiated with the server.
|
read |
Status of the WebSocket.
The state can have the following values:
WebSocket.CONNECTING
(0) WebSocket.OPEN
(1) WebSocket.CLOSING
(2) WebSocket.CLOSED
(3)
|
readwrite |
|
readwrite |
|
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()
.
void abort | ( | ) |
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.
closeCode | Optional code to indicate reason for closure. Typically one of the standard protocol codes, as enumerated by WebSocket.CloseCode . Default is 1000 , or "normal." |
reason | Optional reason text for the closure. Default is an empty string. |
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.
void ping | ( | ArrayBuffer & | payload = ArrayBuffer() | ) |
Send a "ping" to the connected server. The server should respond with a "pong" message.
payload | Optional data to send with the ping. This will be returned by the server in the "pong" message. Default payload value is empty. |
int send | ( | any | data, |
< object|boolean > | options = false |
||
) |
Sends a message to the server.
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.
|
-1
in case of error.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.
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.
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.
void terminate | ( | ) |
Alias for abort()
method.
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.
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".
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.
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".
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.
void readyStateChanged | ( | WebSocket::ReadyState | newState | ) |
This event is emitted when the readyState
property changes.
newState | - the current state value. |
This event has a corresponding onreadyStateChanged
property to which a single event handler may be assigned.
void pong | ( | quint64 | elapsedTime, |
ArrayBuffer & | payload | ||
) |
Emitted when a "pong" message is received from the current server. Two arguments are passed to event listeners:
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.