WebSocket
The WebSocket library provides functionality to create and manage WebSocket connections in Lua.
Creating a WebSocket Connection (These do the same thing)
Function |
Description |
WebSocket.New(url) |
Creates a new WebSocket connection |
WebSocket.new(url) |
Alias for WebSocket.New |
WebSocket.connect(url) |
Alias for WebSocket.New |
WebSocket.Connect(url) |
Alias for WebSocket.New |
url
: A string representing the WebSocket URL to connect to.
Returns a WebSocketClient object.
local ws = WebSocket.New("ws://example.com/socket")
WebSocketClient Methods
Method |
Description |
ws:Send(message) |
Sends a message through the WebSocket connection |
ws:send(message) |
Alias for ws:Send |
ws:Close() |
Closes the WebSocket connection |
ws:close() |
Alias for ws:Close |
message
: A string to be sent.
ws:Send("Hello, server!")
ws:Close()
WebSocketClient Properties
Property |
Description |
ws.OnMessage |
Event that fires when a message is received from the server |
ws.OnClose |
Event that fires when the WebSocket connection is closed |
ws.OnMessage:Connect(function(message)
print("Received:", message)
end)
ws.OnClose:Connect(function()
print("WebSocket connection closed")
end)
Example Usage
local WebSocket = WebSocket
-- Create a new WebSocket connection
local ws = WebSocket.New("ws://example.com/socket")
-- Set up message handler
ws.OnMessage:Connect(function(message)
print("Received:", message)
-- Echo the message back
ws:Send("Echo: " .. message)
end)
-- Set up close handler
ws.OnClose:Connect(function()
print("WebSocket connection closed")
end)
-- Send a message
ws:Send("Hello, server!")
-- Later, when you're done
ws:Close()