WebSocket.connect Asynchronous

  • WebSocket.Connect
  • WebSocket.new
  • syn.websocket.Connect
  • syn.websocket.connect
  • syn.websocket.new
  • websocket.Connect
  • websocket.connect
  • websocket.new

Open a persistent connection to a WebSocket server when your script needs to send and receive messages over time. The returned socket exposes events for incoming messages and closure.

Syntax
Luau
WebSocket.connect(url: string) -> WebSocket

Parameters

Function parameters
ParameterTypeDescription
urlstringServer URL starting with ws:// or wss://.

Returns

WebSocket

A WebSocket with Send, Close, OnMessage, OnClose, and IsClosed.

WebSocket fields
Luau
WebSocket = {
  OnMessage: NativeSignal, OnClose: NativeSignal,
  IsClosed: boolean
}

Usage notes

The connection attempt yields and can fail due to a bad URL, failed handshake, unavailable server, or exhausted connection slots.

Listen for OnClose even if your code never calls Close; the server or a transport limit can close it.

Limits

ResourceLimitWhat happens
Connection slots8 registered or connecting clientsAnother connect attempt raises an error when all slots are occupied. Closing starts cleanup; a slot can remain occupied until that cleanup finishes.
Message size16 MiB per messageAn oversized send is rejected; an oversized incoming message closes the connection. Text messages must be valid UTF-8.
Per-connection queue256 messages and 16 MiB of payload, combining incoming and outgoing messagesExceeding either limit closes the overloaded connection, discards queued payloads, and reports closure through OnClose.
Shared queue budget32 MiB of payload across connectionsA connection that cannot reserve more queue space is closed. An outgoing frame counts toward the budget until its write finishes.
Write deadline10 seconds per outgoing frameA stalled write closes the connection. Returning from Send confirms queuing, not delivery.

Handle connection failures and OnClose as normal lifecycle events. Consume incoming messages and pace outgoing work instead of treating Send as an unlimited buffer. These are transport queue limits; data retained in your own tables is separate.

Differences from sUNC

Kawaii also exposes IsClosed on the returned socket. Send accepts an optional binary flag, documented on its method page.

Example

Example
Luau
local ok, socket = pcall(WebSocket.connect, "wss://echo.websocket.events")
if not ok then
    warn("Connection failed:", socket)
    return
end
socket.OnMessage:Connect(function(message)
    print("Received:", message)
end)
socket.OnClose:Connect(function()
    print("Socket closed")
end)
socket:Send("hello")
task.delay(5, function() socket:Close() end)
Kawaii documentation