WebSockets for Corona HTML5 builds.
Looking for a WebSockets plugin that supports device builds? Click here.
Add websockets_js.js and websockets.lua to the root of your project.
local ws = require("websockets")local function WsListener(event)
if event.type == ws.ONOPEN then
print('connected')
elseif event.type == ws.ONMESSAGE then
print('message', event.data)
elseif event.type == ws.ONCLOSE then
print('disconnected')
elseif event.type == ws.ONERROR then
print('error', event.reason)
end
end
ws.addEventListener(WsListener)
ws.connect('ws://<websocket-url>')
--OR (for secure websockets)
--ws.connect('wss://<websocket-url>')Connect the WebSocket object to a WebSocket endpoint.
ws.connect( ws_url )Make sure your WebSocket event handler is set up before calling this method. See addEventListener.
Disconnect the WebSocket object from the endpoint.
ws.disconnect()Send a message over the WebSocket connection.
ws.send( data )Example
ws.send("Hello WebSocket server")Add the WebSocket event handler. See Setup above.
ws.addEventListener( WsListener )Remove the WebSocket event handler.
ws.removeEventListener()The following event constants are used in the WebSocket event listener. Some events will include addtional data that can be accessed from the event object. See also: addEventListener.
The WebSocket connection is open and ready.
ws.ONOPENEvent Keys
This event contains no event keys.
A WebSocket message has been received.
ws.ONMESSAGEEvent Keys
data
Example
...
local function WsListener(event)
if event.type == ws.ONMESSAGE then
print(event.data) --> message data
end
end
...The WebSocket connection has closed and is no longer available.
ws.ONCLOSEEvent Keys
This event contains no event keys.
A WebSocket error has occurred. This will generally close the connection.
ws.ONERROREvent Keys
reason
Example
...
local function WsListener(event)
if event.type == ws.ONERROR then
print(event.reason) --> error reason
end
end
...local ws = require("websockets")
local function WsListener(event)
if event.type == ws.ONOPEN then
print('connected')
-- send a message
ws.send("Hello")
elseif event.type == ws.ONMESSAGE then
print('message', event.data)
elseif event.type == ws.ONCLOSE then
print('disconnected')
elseif event.type == ws.ONERROR then
print('error', event.reason)
end
end
--connection
ws.addEventListener(WsListener)
ws.connect('ws://demos.kaazing.com/echo')
--disconnection
timer.performWithDelay(5000, function()
ws.disconnect()
ws.removeEventListener(WsListener)
end)©2018 C. Byerley (develephant)