Skip to content
This repository has been archived by the owner on Jul 1, 2018. It is now read-only.

socket library

SquidDev edited this page Apr 27, 2017 · 2 revisions

The socket library allows opening TCP sockets to other computers. It is heavily based off OpenComputer's internet API.

Examples

local connection = socket.connect("127.0.0.1", 1000)

-- Wait for a connection
while not connection.checkConnected() do
    sleep(0.05)
end

while true do
    -- Read the message from 127.0.0.1
    local msg = connection.read()
    if msg and #msg > 0 then
        print(msg)
        -- Stop upon receiving "quit"
        if msg == "quit" then break end
    end
    sleep(0.05)
end

-- Close the handle. If you don't do this then other people won't be able to open sockets!
connection.close()

Configuration

All configuration options live under APIs.Socket:

  • enabled = true: Whether TCP sockets are enabled. If false then this API will not be added to the list.
  • blacklist: List of blacklisted IP addresses. By default this blocks all local network connections. IP addresses can be in CIDR notation for ease of use.
  • whitelist: If specified all IP addresses will be blacklisted apart from those listed here.
  • maxTcpConnections = 4: The maximum number of TCP connections a single computer can have.
  • threads = 4: Number of threads to use to process name lookups.
  • maxRead = 2048: Maximum number of bytes to read from a socket.

Methods

socket library methods

socket.connect(address:string[, port:int])

Connect to a socket on a particular port. This will error if the address is in an incorrect format or too many sockets are open.

socket.websocket(address:string[, headers:table])

Connect to a websocket on the given address. The address can include the port (example.com:8080) and the protocol to use (ws://example.com or wss://example.com).

Connection methods

connection.checkConnected():boolean

Checks if the socket is connected. This returns true if it is connected, false if it isn't or errors if no connection could be made. You should poll this before reading or writing any content from the socket.

while not connection.checkConnected() do 
  sleep(0.05) 
end

connection.close()

Close this socket. You should do this when you have finished using it to ensure that other programs can use sockets.

connection.read([limit:integer]):string|nil

Read a number of bytes to the socket. A string is returned if there is data to be read. nil or an empty string will be returned if no data exists.

connection.write(data:string):integer

Write a number of bytes to the socket. Returns the number of bytes written to the stream.