Skip to content

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 ​

WebSocket()

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:

ConstantDescription
WebSocket.CONNECTING read-only0: connecting
WebSocket.OPEN read-only1: connected
WebSocket.CLOSING read-only2: closing
WebSocket.CLOSED read-only3: ended

Instance properties ​

PropertyDescription
url read-onlyThe URL of the connection
readyState read-onlyThe stage the connection is in
protocol read-onlyThe subprotocol the server selected
maximumMessageSizeThe maximum size of a single received message, in bytes

Instance methods ​

Also inherits addEventListener(), removeEventListener(), and dispatchEvent() from EventTarget.

MethodDescription
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.

EventWhen it fires
openThe connection is established
messageA message arrives
errorThe connection failed, or dropped partway through. Always followed by a close
closeThe 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:

readyStateConstantMeaningWhen it is entered
0WebSocket.CONNECTINGConnecting; messages cannot be sent yetAfter construction
1WebSocket.OPENConnected; messages can be sent and receivedWhen open fires
2WebSocket.CLOSINGClosingAfter close() is called
3WebSocket.CLOSEDEndedWhen 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, close fires, and wasClean is true.
  • The server closes the connection: close fires, and code is the code the server sent. Not verified in the simulator.
  • The connection fails, or drops after it was established: error fires first, then close, with code 1006 and wasClean false. Whether open fired 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.

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 hello back, and Received hello is 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 Error followed by a system error description, then Closed 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 ​

ObjCJS
[session webSocketTaskWithRequest:req] plus [task resume]new WebSocket(url, { headers })
[task sendMessage:msg completionHandler:]await ws.send(data)
[task receiveMessageWithCompletionHandler:], called again after each messagemessage event, fires continuously
[task sendPingWithPongReceiveHandler:]await ws.ping()
[task cancelWithCloseCode:reason:]ws.close(code, reason)
task.maximumMessageSizews.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:

CaseBrowserHere
Second constructor argumentA subprotocol string or arrayAn object: { headers, protocols }; see WebSocket()
Custom request headers on the handshakeNot possiblePossible, with headers
ping()NoneAvailable
maximumMessageSizeNoneAvailable
Return value of send()NoneA Promise
Calling send() before the connection is openThrowsThe returned Promise is rejected
data of a binary messageA Blob by default; binaryType can change it to ArrayBufferAlways a Blob
Properties such as onopenAvailableNone
error eventCarries no reasonCarries message
bufferedAmount, extensions, binaryTypeAvailableNone
Constants such as ws.OPEN on instancesAvailableNone; only on WebSocket
readyState values and the four constants' valuesNumbersThe same

See also ​