WebSocket.OnMessage
Signal that fires when a message is received from the server.
Syntax
WebSocket.OnMessage:Connect(callback: (message: string, isBinary: boolean) -> ()) -> VoltConnectionCallback Parameters
| Parameter | Type | Description |
|---|---|---|
message | string | The received message |
isBinary | boolean | Whether the message arrived as a binary frame |
Returns
| Type | Description |
|---|---|
VoltConnection | A 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)
endRelated
WebSocket.connect- Create connectionWebSocket:Send- Send messagesOnClose- Connection close event