WebSocket. connect Asynchronous
WebSocket.ConnectWebSocket.newsyn.websocket.Connectsyn.websocket.connectsyn.websocket.newwebsocket.Connectwebsocket.connectwebsocket.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.
WebSocket.connect(url: string) -> WebSocketParameters
| Parameter | Type | Description |
|---|---|---|
url | string | Server URL starting with ws:// or wss://. |
Returns
WebSocketA WebSocket with Send, Close, OnMessage, OnClose, and IsClosed.
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
| Resource | Limit | What happens |
|---|---|---|
| Connection slots | 8 registered or connecting clients | Another connect attempt raises an error when all slots are occupied. Closing starts cleanup; a slot can remain occupied until that cleanup finishes. |
| Message size | 16 MiB per message | An oversized send is rejected; an oversized incoming message closes the connection. Text messages must be valid UTF-8. |
| Per-connection queue | 256 messages and 16 MiB of payload, combining incoming and outgoing messages | Exceeding either limit closes the overloaded connection, discards queued payloads, and reports closure through OnClose. |
| Shared queue budget | 32 MiB of payload across connections | A connection that cannot reserve more queue space is closed. An outgoing frame counts toward the budget until its write finishes. |
| Write deadline | 10 seconds per outgoing frame | A 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
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)