/corona-html5-websockets-plugin

WebSockets plugin for Corona HTML5 builds.

Primary LanguageJavaScriptApache License 2.0Apache-2.0

Corona HTML5 WebSockets Plugin

WebSockets for Corona HTML5 builds.

Looking for a WebSockets plugin that supports device builds? Click here.

Install

Add websockets_js.js and websockets.lua to the root of your project.

Require

local ws = require("websockets")

Setup

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>')

API

connect

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

Disconnect the WebSocket object from the endpoint.

ws.disconnect()

send

Send a message over the WebSocket connection.

ws.send( data )

Example

ws.send("Hello WebSocket server")

addEventListener

Add the WebSocket event handler. See Setup above.

ws.addEventListener( WsListener )

removeEventListener

Remove the WebSocket event handler.

ws.removeEventListener()

Event Constants

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.

ONOPEN

The WebSocket connection is open and ready.

ws.ONOPEN

Event Keys

This event contains no event keys.

ONMESSAGE

A WebSocket message has been received.

ws.ONMESSAGE

Event Keys

  • data

Example

...

local function WsListener(event)
 if event.type == ws.ONMESSAGE then
   print(event.data) --> message data
 end
end

...

ONCLOSE

The WebSocket connection has closed and is no longer available.

ws.ONCLOSE

Event Keys

This event contains no event keys.

ONERROR

A WebSocket error has occurred. This will generally close the connection.

ws.ONERROR

Event Keys

  • reason

Example

...

local function WsListener(event)
  if event.type == ws.ONERROR then
    print(event.reason) --> error reason
  end
end

...

Echo Example

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)