WebSocket
WebSocket represents a persistent connection between the app and a server. Once established, the connection stays open, and either side can send the other a message at any time, without a request-and-response exchange. Use it for live quotes, chat, and server push; when one request gets one response, use fetch.
A connection is created with new WebSocket(url). When the constructor returns, the connection is not yet established; it immediately starts connecting in the background and reports the outcome through events: open fires when it connects, message when a message arrives, error on an error, and close when the connection ends.
The URL scheme is wss: (encrypted) or ws: (unencrypted).
Inheritance: EventTarget → WebSocket
WebSocket cannot be subclassed; see Native classes. For how to keep a long-lived connection and send and receive different kinds of messages, see the guide Sending and receiving messages with WebSocket.
Constructor
Creates a connection and starts connecting immediately. Request headers can be added to the handshake request.
Static properties
Four constants, the four possible values of readyState:
| Constant | Description |
|---|---|
WebSocket.CONNECTING read-only | 0: connecting |
WebSocket.OPEN read-only | 1: connected |
WebSocket.CLOSING read-only | 2: closing |
WebSocket.CLOSED read-only | 3: ended |
Instance properties
| Property | Description |
|---|---|
url read-only | The URL of the connection |
readyState read-only | The stage the connection is in |
protocol read-only | The subprotocol the server selected |
maximumMessageSize | The maximum size of a single received message, in bytes |
Instance methods
Also inherits addEventListener(), removeEventListener(), and dispatchEvent() from EventTarget.
| Method | Description |
|---|---|
send() | Sends a text or binary message. Returns a Promise |
ping() | Checks whether the connection is still alive. Returns a Promise |
close() | Closes the connection |
Events
Listen with addEventListener(). There are no properties such as onopen or onmessage.
| Event | When it fires |
|---|---|
open | The connection is established |
message | A message arrives |
error | The connection failed, or dropped partway through. Always followed by a close |
close | The connection ended. Fires only once per connection |
None of the four events can be canceled. Listening for any other name does not throw: it is treated as a custom event and fires only when you dispatch it yourself with dispatchEvent().
Event callbacks all run after the current piece of code finishes (see How the runtime works), so adding listeners right after new WebSocket() does not miss any event. An event that fires before a listener is added is lost; it is not delivered again.
The four stages of a connection
readyState gives the stage the connection is in right now:
readyState | Constant | Meaning | When it is entered |
|---|---|---|---|
0 | WebSocket.CONNECTING | Connecting; messages cannot be sent yet | After construction |
1 | WebSocket.OPEN | Connected; messages can be sent and received | When open fires |
2 | WebSocket.CLOSING | Closing | After close() is called |
3 | WebSocket.CLOSED | Ended | When close fires |
A connection goes through these four stages only once. After it ends, it cannot be reopened; to connect again, create a new WebSocket.
How a connection ends
- The app calls
close(): both sides complete the closing handshake according to the protocol,closefires, andwasCleanistrue. - The server closes the connection:
closefires, andcodeis the code the server sent. Not verified in the simulator. - The connection fails, or drops after it was established:
errorfires first, thenclose, withcode1006andwasCleanfalse. Whetheropenfired tells these two cases apart.
However the connection ends, close fires at the end, exactly once. A dropped connection does not reconnect automatically.
Until the connection ends, the runtime keeps the WebSocket object alive. Even if the app's code does not keep a reference to it, the connection keeps working and events keep firing. After close fires, the runtime no longer keeps it.
Examples
Send a message and close after the reply
The code below connects to a public service that echoes messages back, sends one text message, and closes the connection after the reply arrives. It needs no UI and runs as-is at the top level of main.js.
const ws = new WebSocket('wss://echo.websocket.org');
ws.addEventListener('open', () => {
console.log('Connected');
ws.send('hello');
});
ws.addEventListener('message', (e) => {
const data = /** @type {WebSocketMessageEvent} */ (e).data;
console.log('Received', data);
if (data === 'hello') ws.close(1000, 'bye');
});
ws.addEventListener('error', (e) => {
console.log('Error', /** @type {WebSocketErrorEvent} */ (e).message);
});
ws.addEventListener('close', (e) => {
const { code, wasClean } = /** @type {WebSocketCloseEvent} */ (e);
console.log('Closed', code, wasClean);
});Effect
- Once connected, logs
Connected. - The server sends
helloback, andReceived hellois logged. This service may first send a welcome message of its own when the connection opens; that one is logged too. - When closing completes, logs
Closed 1000 true. - If the connection fails, logs
Errorfollowed by a system error description, thenClosed 1006 false.
The event callback's parameter has the generic Event type, so it needs a cast before you can read fields such as data, message, and code; that is what /** @type {...} */ (e) above does.
This code has not been run as a whole in the simulator. Each API it uses has been run against the same service in the acceptance tests.
For more patterns, see the guide Sending and receiving messages with WebSocket.
Corresponding iOS API
| ObjC | JS |
|---|---|
[session webSocketTaskWithRequest:req] plus [task resume] | new WebSocket(url, { headers }) |
[task sendMessage:msg completionHandler:] | await ws.send(data) |
[task receiveMessageWithCompletionHandler:], called again after each message | message event, fires continuously |
[task sendPingWithPongReceiveHandler:] | await ws.ping() |
[task cancelWithCloseCode:reason:] | ws.close(code, reason) |
task.maximumMessageSize | ws.maximumMessageSize |
URLSession:webSocketTask:didOpenWithProtocol: | open event |
URLSession:webSocketTask:didCloseWithCode:reason: | close event with wasClean true |
URLSession:task:didCompleteWithError: | error event plus close event with code 1006 |
NSURLSessionWebSocketTask itself cannot be used directly from JS.
Differences from the web
The name and most members are the same as the browser's WebSocket. The differences:
| Case | Browser | Here |
|---|---|---|
| Second constructor argument | A subprotocol string or array | An object: { headers, protocols }; see WebSocket() |
| Custom request headers on the handshake | Not possible | Possible, with headers |
ping() | None | Available |
maximumMessageSize | None | Available |
Return value of send() | None | A Promise |
Calling send() before the connection is open | Throws | The returned Promise is rejected |
data of a binary message | A Blob by default; binaryType can change it to ArrayBuffer | Always a Blob |
Properties such as onopen | Available | None |
error event | Carries no reason | Carries message |
bufferedAmount, extensions, binaryType | Available | None |
Constants such as ws.OPEN on instances | Available | None; only on WebSocket |
readyState values and the four constants' values | Numbers | The same |
See also
- Sending and receiving messages with WebSocket: text, binary, JSON, reconnecting, heartbeats, the app returning to the foreground
fetch: when one request gets one response;Blobis also described there- Timers:
setIntervalandsetTimeout, used for heartbeats and reconnecting application: theforegroundevent, when the app returns to the foregroundURL: building and checking connection URLs- How the runtime works: when event callbacks run