The socket
library provides a way to easily read and write binary data.
-- Create a new socket
local s = require("socket").new();
-- Attach event handler
s:onconnect(function ()
s:write("foo");
end);
-- Connect socket
s:connect("localhost", 1234);
Creates a new socket.
local s = require("socket").new();
Connects to the specifed host and port. Invokes onconnect
.
local s = require("socket").new();
s:connect("localhost", 1234);
Checks if the socket is currently connected.
local s = require("socket").new();
print(s:connected()); -- false
Writes raw data to the socket. Use a buffer for easy data handling.
local s = require("socket").new();
s:onconnect(function ()
-- write raw data
s:write("abc");
-- write data from buffer
local b = require("buffer").new("utf8");
b:writestring("i support unicode åäö");
s:write(b:read());
end);
Closes the socket if it is connected. Invokes onclose
.
local s = require("socket").new();
s:onconnect(function ()
s:close();
end);
Callback to invoke when connection is established.
local s = require("socket").new();
s:onconnect(function ()
end);
Callback to invoke when raw data
is received. Use a buffer for easy data handling.
local s = require("socket").new();
s:ondata(function (data)
print(data);
-- read data to buffer
local b = require("buffer").new("utf8");
b:write(data);
print(b:readstring());
end);
Callback to invoke when connection is broken.
local s = require("socket").new();
s:onconnect(function ()
end);
Callback to invoke when an error occurs.
local s = require("socket").new();
s:onerror(function ( err )
print(err);
end);
s:connect("asdf", 1234);