WebSockets

Last update:2024-08-14 19:50:33

The WebSocket API allows for real-time, bidirectional communication with your CDNetworks Edge Cloud Apps Functions.

Constructor

new WebSocketPair()

Return Value: A WebSocketPair object.

Description: The WebSocketPair object contains two WebSocket objects, representing the client and server sides of the connection. You can conveniently access these objects using array destructuring:

let [client, server] = Object.values(new WebSocketPair());

Methods

accept()

Description: Accepts an incoming WebSocket connection request, allowing the Edge Cloud Apps Function to begin handling WebSocket messages.

addEventListener()

addEventListener(event: WebSocketEvent, callbackFunction: Function)

Parameters:

Parameter Name Type Description
event WebSocketEvent The WebSocket event to listen for.
callbackFunction Function The function to be called when the specified event occurs.

Description: Adds an event listener to a WebSocket object. The callback function will be executed when the specified event occurs.

close()

close(code?: number, reason?: string)

Parameters:

Parameter Name Type Description
code number Optional. An integer representing the reason code for closing the connection. Follows the status codes defined in the WebSocket protocol specification.
reason string Optional. A human-readable string explaining the reason for closing the connection.

Description: Closes the WebSocket connection.

send()

send(message: string \| ArrayBuffer \| ArrayBufferView)

Parameters:

  • message: The message to be sent. It can be a string, an ArrayBuffer, or an ArrayBufferView.

Description: Sends a message to the other end of the connection.

Events

close

Description: Triggered when the WebSocket connection is closed.

error

Description: Triggered when an error occurs on the WebSocket connection.

message

Description: Triggered when the WebSocket connection receives a message. The event object contains the received data.

Note:

WebSocket messages received by an Edge Cloud Apps Function are limited to a size of 1 MiB (1048576). If a larger message is sent, the WebSocket will be automatically closed with a 1009 “Message Too Big” response.

Types

Message

Property Name Type Description
data any The received message data.
type string The message type, defaults to “message.”

References

Is the content of this document helpful to you?
Yes
I have suggestion
Submitted successfully! Thank you very much for your feedback, we will continue to strive to do better!