WebSocket.OnMessage

Signal that fires when a message is received from the server.

Syntax

WebSocket.OnMessage:Connect(callback: (message: string, isBinary: boolean) -> ()) -> VoltConnection

Callback Parameters

ParameterTypeDescription
messagestringThe received message
isBinarybooleanWhether the message arrived as a binary frame

Returns

TypeDescription
VoltConnectionA connection that can be disconnected

Description

OnMessage is a VoltSignal that fires for each message frame received from the server. Text and binary payloads are both returned as Luau strings; use isBinary to distinguish the frame type.

Example

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

ws.OnMessage:Connect(function(message, isBinary)
    print("Received:", message, "binary:", isBinary)
end)

ws:Send("Hello!")

JSON Messages

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

ws.OnMessage:Connect(function(message, isBinary)
    if isBinary then
        return
    end

    local data = HttpService:JSONDecode(message)

    if data.type == "update" then
        print("Update:", data.payload)
    elseif data.type == "error" then
        warn("Error:", data.message)
    end
end)

Message Queue Pattern

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

ws.OnMessage:Connect(function(message, isBinary)
    table.insert(messageQueue, {
        content = message,
        binary = isBinary,
        time = os.time()
    })
end)

-- Process messages elsewhere
local function processQueue()
    for _, msg in ipairs(messageQueue) do
        print(msg.time, msg.content, "binary:", msg.binary)
    end
    table.clear(messageQueue)
end