Skip to content

WebSocket class

The WebSocket class provides a lightweight interface for establishing and working with WebSocket connections. It allows scripts to send and receive messages over a persistent connection to a WebSocket server.

Keep in mind that this is client-only, meaning you won't be able to create a WebSocket server.


Constructor

Attempts to create a new connection to the provided URL. The URL must be a valid WebSocket server URL, typically starting with ws:// (unsecure) or wss:// (secure).

function WebSocket.connect(url: string): WebSocket

Parameters

Parameter Description
url A WebSocket URL.

Events

Signals that allow you handle events that occur during the WebSocket's lifetime, such as opening, receiving messages, or closing.

Event Description
OnMessage(message: string): () Triggered when a message is received over the WebSocket connection.
OnClose(): () Triggered when the WebSocket connection closes.

Methods

Method Description
Send(message: string): () Send a message over the WebSocket connection.
Close(): () Closes the WebSocket connection.

Examples

Using the OnMessage event, and Send method

Responding to incoming messages
1
2
3
4
5
local ws = WebSocket.connect("ws://echo.websocket.events")
ws.OnMessage:Connect(function(message)
    print(message)
end)
ws:Send("Hello") -- Output: Hello

Using the OnClose event, and Close method

Receive a closing message and catch it via OnClose
1
2
3
4
5
local ws = WebSocket.connect("ws://echo.websocket.events")
ws.OnClose:Connect(function()
    print("Closed")
end)
ws:Close() -- Output: Closed