class WebSocketServer

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

A WebSocket server.

Supports plain ws:// server sockets only; WSS/certificate configuration is not exposed. Use { noServer: true } together with an http/https server upgrade listener to accept ws:///wss:// upgrades on an existing server.

Example

const wss = new WebSocketServer({ port: 8081, host: "127.0.0.1" });
wss.on("connection", (ws) => {
  ws.on("message", (event) => ws.send(event.data));
});

Index

Constructors

Methods

new WebSocketServer(options, callback)

new WebSocketServer(
  options?: {
    port?: number;
    host?: string;
    noServer?: boolean;
    protocols?: string | string[];
    selectProtocol?: (req: any, offeredProtocols: string[]) => string;
  },
  callback?: (ws: WebSocketConnection, req: any) => void,
);

Constructs a new instance of the WebSocketServer class

ParameterTypeDescription
optional optionsobjectserver options. noServer: true creates a server with no acceptor for use with handleUpgrade. selectProtocol(req, offered) chooses a subprotocol during upgrade handling.
optional options.port number
optional options.host string
optional options.noServer boolean
optional options.protocols string | string[]
optional options.selectProtocol (req: any, offeredProtocols: string[]) => string
optional callback(ws: WebSocketConnection, req: any) => voidan optional connection listener.

close(callback)

Stops the server.

close(callback?: () => void): void;
NameTypeDescription
optional callback() => void

emit(type, args)

Emits an event to registered listeners.

emit(type: string, ...args: any[]): boolean;
NameTypeDescription
typestring
argsany[]
Return Valueboolean

handleUpgrade(req, socket, head, callback)

Completes a WebSocket handshake on an upgrade socket obtained from an HTTP server upgrade event.

handleUpgrade(
  req: any,
  socket: any,
  head: any,
  callback: (ws: WebSocketConnection) => void,
): void;
NameTypeDescription
reqany
socketany
headany
callback(ws: WebSocketConnection) => void

listen(optionsOrPort, callback)

Begins listening (when not in noServer mode).

listen(
  optionsOrPort: number | { port?: number; host?: string },
  callback?: () => void,
): void;
NameTypeDescription
optionsOrPortnumber | { port?: number; host?: string }
optional callback() => void

off(type, listener)

Removes an event listener.

off(type: string, listener: (...args: any[]) => void): this;
NameTypeDescription
typestring
listener(...args: any[]) => void
Return Valuethis

on(type, listener)

Registers an event listener (listening, connection, close, error).

on(type: string, listener: (...args: any[]) => void): this;
NameTypeDescription
typestring
listener(...args: any[]) => void
Return Valuethis

once(type, listener)

Registers a one-shot event listener.

once(type: string, listener: (...args: any[]) => void): this;
NameTypeDescription
typestring
listener(...args: any[]) => void
Return Valuethis