connect(url, ex, listeners)

Connects to a websocket service at the given url. Returns a websocket object.


local websocket = require "util.websocket";
local ws = websocket.connect("wss://", nil, {
    onopen = function (ws)
        ws:send("hello world");
    onmessage = function (ws, data)
        print("Received data:", data);


You can optionally provide some advanced options by passing an ex table. If none of these are required, you may pass nil. If you pass a table, it can optionally include any of the following fields:


Set the Websocket protocol - either specify a single string, or an array of strings.


A table of custom HTTP headers:

    ex.headers = {
        ["Custom-Header"] = "onetwothreefour";


A string specifying supported websocket extensions.


A LuaSec-compatible sslctx object (overrides the default set by the HTTP library, if specified).



The websocket connection was opened.

=== onclose(ws, close_code, close_message === For more in

The websocket connection was closed.

onmessage(ws, data, type)

The websocket connection received a message.

onerror(ws, error)

The websocket connection encountered an error.

Websocket objects

The websocket object returned by the connect() function has the following methods:

ws:send(data, opcode)

Send the given string of data over the websocket connection.

You can optionally specify an opcode, which may be the string "text" or "binary" or a raw hex opcode. If not specified, it defaults to "text".

ws:close(code, reason)

Close the websocket connection. If code is not specified, it defaults to 1000. If reason is specified, it must be a string that is not longer than 123 bytes.