search
element with form functionality — Last Updated 1 December 2021To enable web applications to maintain bidirectional communications with server-side processes,
this specification introduces the WebSocket
interface.
This interface does not allow for raw access to the underlying network. For example, this interface could not be used to implement an IRC client without proxying messages through a custom server.
WebSocket
interfaceSupport in all current engines.
socket = new WebSocket(url [, protocols ])
Creates a new WebSocket
object, immediately establishing the associated
WebSocket connection.
url is a string giving the URL over which the connection is
established. Only "ws
" or "wss
" schemes are
allowed; others will cause a "SyntaxError
" DOMException
.
URLs with fragments will also cause such an
exception.
protocols is either a string or an array of strings. If it is a string, it is
equivalent to an array consisting of just that string; if it is omitted, it is equivalent to the
empty array. Each string in the array is a subprotocol name. The connection will only be
established if the server reports that it has selected one of these subprotocols. The
subprotocol names have to match the requirements for elements that comprise the value of Sec-WebSocket-Protocol
fields as defined by
The WebSocket protocol. [WSP]
socket.send(data)
Transmits data using the WebSocket connection. data can be a string, a
Blob
, an ArrayBuffer
, or an ArrayBufferView
.
socket.close([ code ] [, reason ])
Closes the WebSocket connection, optionally using code as the WebSocket connection close code and reason as the the WebSocket connection close reason.
socket.url
Returns the URL that was used to establish the WebSocket connection.
socket.readyState
Returns the state of the WebSocket
object's connection. It can have the values
described below.
socket.bufferedAmount
Returns the number of bytes of application data (UTF-8 text and binary data) that have been
queued using send()
but not yet been transmitted to the
network.
If the WebSocket connection is closed, this attribute's value will only increase with each
call to the send()
method. (The number does not reset
to zero once the connection closes.)
socket.extensions
Returns the extensions selected by the server, if any.
socket.protocol
Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.
socket.binaryType [ = value ]
Returns a string that indicates how binary data from the WebSocket
object is
exposed to scripts:
blob
"Binary data is returned in Blob
form.
arraybuffer
"Binary data is returned in ArrayBuffer
form.
Can be set, to change how binary data is returned. The default is "blob
".
The readyState
attribute can have the
following values:
CONNECTING
(numeric value 0)OPEN
(numeric value 1)CLOSING
(numeric value 2)close()
method has been invoked.CLOSED
(numeric value 3)The close()
method does not discard
previously sent messages before starting the WebSocket closing handshake — even if, in
practice, the user agent is still busy sending those messages, the handshake will only start after
the messages are sent.
In this simple example, the bufferedAmount
attribute is used to ensure that updates are sent either at the rate of one update every 50ms, if
the network can handle that rate, or at whatever rate the network can handle, if that is
too fast.
var socket = new WebSocket( 'ws://game.example.com:12010/updates' );
socket. onopen = function () {
setInterval( function () {
if ( socket. bufferedAmount == 0 )
socket. send( getUpdateData());
}, 50 );
};
The bufferedAmount
attribute can also be
used to saturate the network without sending the data at a higher rate than the network can
handle, though this requires more careful monitoring of the value of the attribute over time.
The following are the event handlers (and their corresponding event handler event types) supported,
as event handler IDL attributes, by all objects implementing the
WebSocket
interface:
Event handler | Event handler event type |
---|---|
onopen Support in all current engines. Firefox7+Safari5+Chrome4+ Opera12.1+Edge79+ Edge (Legacy)12+Internet Explorer10+ Firefox Android7+Safari iOS4.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+ | open
|
onmessage Support in all current engines. Firefox7+Safari5+Chrome4+ Opera12.1+Edge79+ Edge (Legacy)12+Internet Explorer10+ Firefox Android7+Safari iOS4.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+ | message
|
onerror Support in all current engines. Firefox7+Safari5+Chrome5+ Opera12.1+Edge79+ Edge (Legacy)12+Internet Explorer10+ Firefox Android7+Safari iOS4.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+ | error
|
onclose Support in all current engines. Firefox7+Safari5+Chrome4+ Opera12.1+Edge79+ Edge (Legacy)12+Internet Explorer10+ Firefox Android7+Safari iOS4.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+ | close
|
Here is an example of how to define a handler for the message
event in the case of text frames:
mysocket. onmessage = function ( event) {
if ( event. data == 'on' ) {
turnLampOn();
} else if ( event. data == 'off' ) {
turnLampOff();
}
};
The protocol here is a trivial one, with the server just sending "on" or "off" messages.
The WebSocket protocol defines Ping and Pong frames that can be used for keep-alive, heart-beats, network status probing, latency instrumentation, and so forth. These are not currently exposed in the API.
CloseEvent
interfaceSupport in all current engines.
WebSocket
objects use the CloseEvent
interface for their close
events:
event.wasClean
Returns true if the connection closed cleanly; false otherwise.
event.code
Returns the WebSocket connection close code provided by the server.
event.reason
Returns the WebSocket connection close reason provided by the server.