WebSocket.OnClose

Signal that fires when the WebSocket connection is closed.

Syntax

WebSocket.OnClose:Connect(callback: () -> ()) -> VoltConnection

Callback Parameters

This callback receives no parameters.

Returns

TypeDescription
VoltConnectionA connection that can be disconnected

Description

OnClose is a VoltSignal that fires after a local Close() or a remote close. Volt may reconnect automatically after a remote close; IsClosed becomes true only when the client is closed locally.

Example

local ws = WebSocket.connect("wss://your-server.example/socket")

ws.OnClose:Connect(function()
    print("Connection closed")
end)

-- Later...
ws:Close()

Reconnection Pattern

local function createConnection()
    local ws = WebSocket.connect("wss://your-server.example/socket")

    ws.OnClose:Connect(function()
        print("Disconnected, reconnecting in 5 seconds...")
        task.wait(5)
        createConnection()
    end)

    ws.OnMessage:Connect(function(msg)
        print("Message:", msg)
    end)

    return ws
end

local connection = createConnection()

Cleanup on Close

local ws = WebSocket.connect("wss://your-server.example/socket")

ws.OnClose:Connect(function()
    print("Cleaning up...")
    -- Perform cleanup tasks
end)

-- Check connection state before sending
if not ws.IsClosed then
    ws:Send("Hello!")
end