net.websocket
connect(url, ex, listeners)
Connects to a websocket service at the given url
.
Returns a websocket object.
Example:
local websocket = require "util.websocket";
local ws = websocket.connect("wss://example.com/test", nil, {
= function (ws)
onopen :send("hello world");
wsend;
= function (ws, data)
onmessage print("Received data:", data);
end;
})
ex
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:
ex.protocol
Set the Websocket protocol - either specify a single string, or an array of strings.
ex.headers
A table of custom HTTP headers:
.headers = {
ex["Custom-Header"] = "onetwothreefour";
}
ex.extensions
A string specifying supported websocket extensions.
ex.sslctx
A LuaSec-compatible sslctx object (overrides the default set by the HTTP library, if specified).
listeners
onopen(ws)
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.