class WebSocket

Supported only in the v8 engine. Introduced in Max v9.2.0.

A WebSocket client.

URLs must be absolute ws:// or wss:// URLs. There is no binaryType, extensions, or custom-header API.

Example

const ws = new WebSocket("ws://127.0.0.1:8081", ["chat"]);
ws.onopen = () => ws.send("hello");
ws.onmessage = (event) => post(event.data, "\n");
ws.onerror = (event) => post(event.error.message, "\n");

Index

Constructors

Properties

Methods

new WebSocket(url, protocols)

new WebSocket(url: string, protocols?: string | string[]);

Constructs a new instance of the WebSocket class

ParameterTypeDescription
urlstringan absolute ws:// or wss:// URL.
optional protocolsstring | string[]one or more subprotocol names to offer.

addEventListener(type, listener)

Registers an event listener.

addEventListener(type: string, listener: (...args: any[]) => void): void;
NameTypeDescription
typestring
listener(...args: any[]) => void

bufferedAmount number read-only

The number of queued outbound bytes.

close(code, reason)

Closes the connection.

close(code?: number, reason?: string): void;
NameTypeDescription
optional codenumber
optional reasonstring

onclose ((event: WebSocketCloseEvent) => void) | null

Called when the connection closes.

ondrain ((event: { type: string }) => void) | null

Called when queued outbound bytes drop below the high-water mark.

onerror ((event: WebSocketErrorEvent) => void) | null

Called on error.

onmessage ((event: WebSocketMessageEvent) => void) | null

Called when a message arrives.

onopen ((event: { type: string }) => void) | null

Called when the connection opens.

protocol string read-only

The negotiated subprotocol, or "" until the handshake selects one.

readyState number read-only

The connection state (CONNECTING, OPEN, CLOSING, CLOSED).

removeEventListener(type, listener)

Removes an event listener.

removeEventListener(type: string, listener: (...args: any[]) => void): void;
NameTypeDescription
typestring
listener(...args: any[]) => void

send(value)

Sends data. Strings are sent as text frames; other values are coerced through buffer.IOBuffer and sent as binary frames.

send(
  value: string | buffer.IOBuffer | ArrayBuffer | ArrayBufferView,
): boolean;
NameTypeDescription
valuestring | buffer.IOBuffer | ArrayBuffer | ArrayBufferView
Return Valuebooleanfalse once queued outbound bytes exceed the high-water mark.

url string read-only

The connection URL.