sock.lua

A Lua networking library for LÖVE games.

Tables

🔗

CONNECTING_STATES

States that represent the client connecting to a server.

Fields:

connecting
In the process of connecting to the server.
acknowledging_connect
connection_pending
connection_succeeded
🔗

CONNECTION_STATES

All of the possible connection statuses for a client connection.

Fields:

disconnected
Disconnected from the server.
connecting
In the process of connecting to the server.
acknowledging_connect
connection_pending
connection_succeeded
connected
Successfully connected to the server.
disconnect_later
Disconnecting, but only after sending all queued packets.
disconnecting
In the process of disconnecting from the server.
acknowledging_disconnect
zombie
unknown

See also:

🔗

DISCONNECTING_STATES

States that represent the client disconnecting from a server.

Fields:

disconnect_later
Disconnecting, but only after sending all queued packets.
disconnecting
In the process of disconnecting from the server.
acknowledging_disconnect
🔗

SEND_MODES

Valid modes for sending messages.

Fields:

reliable
Message is guaranteed to arrive, and arrive in the order in which it is sent.
unsequenced
Message has no guarantee on the order that it arrives.
unreliable
Message is not guaranteed to arrive.

Class Server

Manages all clients and receives network events.

🔗

Server:destroy()

Destroys the server and frees the port it is bound to.

🔗

Server:enableCompression()

Enables an adaptive order-2 PPM range coder for the transmitted data of all peers.

Both the client and server must both either have compression enabled or disabled.

Note: lua-enet does not currently expose a way to disable the compression after it has been enabled.

🔗

Server:getAddress()

Get the IP address or hostname that the server was created with.

Returns:

  1. string
🔗

Server:getClient(peer)

Gets the Client object associated with an enet peer.

Parameters:

peer peer
An enet peer.

Returns:

  1. Client Object associated with the peer.
🔗

Server:getClientByConnectId(connectId)

Gets the Client object that has the given connection id.

Parameters:

number connectId
The unique client connection id.

Returns:

  1. Client
🔗

Server:getClientByIndex(index)

Get the Client object that has the given peer index.

Parameters:

index

Returns:

  1. Client
🔗

Server:getClientCount()

Get the number of Clients that are currently connected to the server.

Returns:

  1. number The number of active clients.
🔗

Server:getClients()

Get the table of Clients actively connected to the server.

Returns:

  1. {Client,...}
🔗

Server:getDefaultSendMode()

Get the default send mode.

Returns:

  1. string

See also:

🔗

Server:getLastServiceTime()

Get the last time when network events were serviced.

Returns:

  1. number Timestamp of the last time events were serviced.
🔗

Server:getMaxChannels()

Get the number of allocated channels.

Channels are zero-indexed, e.g. 16 channels allocated means that the maximum channel that can be used is 15.

Returns:

  1. number Number of allocated channels.
🔗

Server:getMaxPeers()

Get the number of allocated slots for peers.

Returns:

  1. number Number of allocated slots.
🔗

Server:getMessageTimeout()

Get the timeout for packets.

Returns:

  1. number Time to wait for incoming packets in milliseconds. initial default is 0.
🔗

Server:getPeerByIndex(index)

Get the enet_peer that has the given index.

Parameters:

index

Returns:

  1. enet_peer The underlying enet peer object.
🔗

Server:getPort()

Get the port that the server is hosted on.

Returns:

  1. number
🔗

Server:getSendMode()

Get the current send mode.

Returns:

  1. string

See also:

🔗

Server:getSocketAddress()

Get the socket address of the host.

Returns:

  1. string A description of the socket address, in the format "A.B.C.D:port" where A.B.C.D is the IP address of the used socket.
🔗

Server:getTotalReceivedData()

Get the total received data since the server was created.

Returns:

  1. number The total received data in bytes.
🔗

Server:getTotalReceivedPackets()

Get the total number of packets (messages) received since the server was created.

Returns:

  1. number The total number of received packets.

See also:

🔗

Server:getTotalSentData()

Get the total sent data since the server was created.

Returns:

  1. number The total sent data in bytes.
🔗

Server:getTotalSentPackets()

Get the total number of packets (messages) sent since the server was created.

Everytime a message is sent or received, the corresponding figure is incremented. Therefore, this is not necessarily an accurate indicator of how many packets were actually exchanged over the network.

Returns:

  1. number The total number of sent packets.
🔗

Server:log(event, data)

Log an event.

Alias for Server.logger:log.

Parameters:

string event
The type of event that happened.
string data
The message to log.

Usage:

    if somethingBadHappened then
        server:log("error", "Something bad happened!")
    end
🔗

Server:on(event, callback)

Add a callback to an event.

Parameters:

string event
The event that will trigger the callback.
function callback
The callback to be triggered.

Returns:

  1. function The callback that was passed in.

Usage:

    server:on("connect", function(data, client)
        print("Client connected!")
    end)
🔗

Server:removeCallback(callback)

Remove a specific callback for an event.

Parameters:

function callback
The callback to remove.

Returns:

  1. boolean Whether or not the callback was removed.

Usage:

    local callback = server:on("chatMessage", function(message)
        print(message)
    end)
    server:removeCallback(callback)
🔗

Server:resetSendSettings()

Reset all send options to their default values.

🔗

Server:sendToAll(event, data)

Send a message to all clients.

Parameters:

string event
The event to trigger with this message.
data
The data to send.

Usage:

    server:sendToAll("gameStarting", true)
🔗

Server:sendToAllBut(client, event, data)

Send a message to all clients, except one.

Useful for when the client does something locally, but other clients need to be updated at the same time. This way avoids duplicating objects by never sending its own event to itself in the first place.

Parameters:

Client client
The client to not receive the message.
string event
The event to trigger with this message.
data
The data to send.
🔗

Server:sendToPeer(peer, event, data)

Send a message to a single peer.

Useful to send data to a newly connected player without sending to everyone who already received it.

Parameters:

enet_peer peer
The enet peer to receive the message.
string event
The event to trigger with this message.
data
data to send to the peer.

Usage:

    server:sendToPeer(peer, "initialGameInfo", {...})
🔗

Server:setBandwidthLimit(incoming, outgoing)

Set the incoming and outgoing bandwidth limits.

Parameters:

number incoming
The maximum incoming bandwidth in bytes.
number outgoing
The maximum outgoing bandwidth in bytes.
🔗

Server:setDefaultSendChannel(channel)

Set the default send channel for all future outgoing messages.

The initial default is 0.

Parameters:

number channel
Channel to send data on.
🔗

Server:setDefaultSendMode(mode)

Set the default send mode for all future outgoing messages.

The initial default is "reliable".

Parameters:

string mode
A valid send mode.

See also:

🔗

Server:setMaxChannels(limit)

Set the maximum number of channels.

Parameters:

number limit
The maximum number of channels allowed. If it is 0, then the maximum number of channels available on the system will be used.
🔗

Server:setMessageTimeout(timeout)

Set the timeout to wait for packets.

Parameters:

number timeout
Time to wait for incoming packets in milliseconds. The initial default is 0.
🔗

Server:setSchema(event, schema)

Set the data schema for an event.

Schemas allow you to set a specific format that the data will be sent. If the client and server both know the format ahead of time, then the table keys do not have to be sent across the network, which saves bandwidth.

Parameters:

string event
The event to set the data schema for.
{string,...} schema
The data schema.

Usage:

    server = sock.newServer(...)
    client = sock.newClient(...)
    
    -- Without schemas
    client:send("update", {
        x = 4,
        y = 100,
        vx = -4.5,
        vy = 23.1,
        rotation = 1.4365,
    })
    server:on("update", function(data, client)
        -- data = {
        --    x = 4,
        --    y = 100,
        --    vx = -4.5,
        --    vy = 23.1,
        --    rotation = 1.4365,
        -- }
    end)
    
    
    -- With schemas
    server:setSchema("update", {
        "x",
        "y",
        "vx",
        "vy",
        "rotation",
    })
    -- client no longer has to send the keys, saving bandwidth
    client:send("update", {
        4,
        100,
        -4.5,
        23.1,
        1.4365,
    })
    server:on("update", function(data, client)
        -- data = {
        --    x = 4,
        --    y = 100,
        --    vx = -4.5,
        --    vy = 23.1,
        --    rotation = 1.4365,
        -- }
    end)
🔗

Server:setSendChannel(channel)

Set the send channel for the next outgoing message.

The channel will be reset after the next message. Channels are zero-indexed and cannot exceed the maximum number of channels allocated. The initial default is 0.

Parameters:

number channel
Channel to send data on.

Usage:

    server:setSendChannel(2) -- the third channel
    server:sendToAll("importantEvent", "The message")
🔗

Server:setSendMode(mode)

Set the send mode for the next outgoing message.

The mode will be reset after the next message is sent. The initial default is "reliable".

Parameters:

string mode
A valid send mode.

See also:

Usage:

    server:setSendMode("unreliable")
    server:sendToAll("playerState", {...})
🔗

Server:setSerialization(serialize, deserialize)

Set the serialization functions for sending and receiving data.

Both the client and server must share the same serialization method.

Parameters:

function serialize
The serialization function to use.
function deserialize
The deserialization function to use.

Usage:

    bitser = require "bitser" -- or any library you like
    server = sock.newServer("localhost", 22122)
    server:setSerialization(bitser.dumps, bitser.loads)
🔗

Server:update()

Check for network events and handle them.

Class Client

Connects to servers.

🔗

Client:connect(code)

Connect to the chosen server.

Connection will not actually occur until the next time Client:update is called.

Parameters:

optional number code
A number that can be associated with the connect event.
🔗

Client:disconnect(code)

Disconnect from the server, if connected.

The client will disconnect the next time that network messages are sent.

Parameters:

optional number code
A code to associate with this disconnect event.
🔗

Client:disconnectLater(code)

Disconnect from the server, if connected.

The client will disconnect after sending all queued packets.

Parameters:

optional number code
A code to associate with this disconnect event.
🔗

Client:disconnectNow(code)

Disconnect from the server, if connected.

The client will disconnect immediately.

Parameters:

optional number code
A code to associate with this disconnect event.
🔗

Client:enableCompression()

Enables an adaptive order-2 PPM range coder for the transmitted data of all peers.

Both the client and server must both either have compression enabled or disabled.

Note: lua-enet does not currently expose a way to disable the compression after it has been enabled.

🔗

Client:getAddress()

Get the IP address or hostname that the client was created with.

Returns:

  1. string
🔗

Client:getConnectId()

Get the unique connection id, if connected.

Returns:

  1. number The connection id.
🔗

Client:getDefaultSendMode()

Get the default send mode.

Returns:

  1. string

See also:

🔗

Client:getIndex()

Get the index of the enet peer.

All peers of an ENet host are kept in an array. This function finds and returns the index of the peer of its host structure.

Returns:

  1. number The index of the peer.
🔗

Client:getLastServiceTime()

Get the last time when network events were serviced.

Returns:

  1. number Timestamp of the last time events were serviced.
🔗

Client:getMaxChannels()

Get the number of allocated channels.

Channels are zero-indexed, e.g. 16 channels allocated means that the maximum channel that can be used is 15.

Returns:

  1. number Number of allocated channels.
🔗

Client:getMessageTimeout()

Get the timeout for packets.

Returns:

  1. number Time to wait for incoming packets in milliseconds. initial default is 0.
🔗

Client:getPeerByIndex(index)

Get the enet_peer that has the given index.

Parameters:

index

Returns:

  1. enet_peer The underlying enet peer object.
🔗

Client:getPort()

Get the port that the client is connecting to.

Returns:

  1. number
🔗

Client:getRoundTripTime()

Return the round trip time (RTT, or ping) to the server, if connected.

It can take a few seconds for the time to approach an accurate value.

Returns:

  1. number The round trip time.
🔗

Client:getSendMode()

Get the current send mode.

Returns:

  1. string

See also:

🔗

Client:getSocketAddress()

Get the socket address of the host.

Returns:

  1. string A description of the socket address, in the format "A.B.C.D:port" where A.B.C.D is the IP address of the used socket.
🔗

Client:getState()

Get the current connection state, if connected.

Returns:

  1. string The connection state.

See also:

🔗

Client:getTotalReceivedData()

Get the total received data since the server was created.

Returns:

  1. number The total received data in bytes.
🔗

Client:getTotalReceivedPackets()

Get the total number of packets (messages) received since the client was created.

Returns:

  1. number The total number of received packets.

See also:

🔗

Client:getTotalSentData()

Get the total sent data since the server was created.

Returns:

  1. number The total sent data in bytes.
🔗

Client:getTotalSentPackets()

Get the total number of packets (messages) sent since the client was created.

Everytime a message is sent or received, the corresponding figure is incremented. Therefore, this is not necessarily an accurate indicator of how many packets were actually exchanged over the network.

Returns:

  1. number The total number of sent packets.
🔗

Client:isConnected()

Gets whether the client is connected to the server.

Returns:

  1. boolean Whether the client is connected to the server.

Usage:

    client:connect()
    client:isConnected() -- false
    -- After a few client updates
    client:isConnected() -- true
🔗

Client:isConnecting()

Gets whether the client is connecting to the server.

Returns:

  1. boolean Whether the client is connected to the server.

Usage:

    client:connect()
    client:isConnecting() -- true
    -- After a few client updates
    client:isConnecting() -- false
    client:isConnected() -- true
🔗

Client:isDisconnected()

Gets whether the client is disconnected from the server.

Returns:

  1. boolean Whether the client is connected to the server.

Usage:

    client:disconnect()
    client:isDisconnected() -- false
    -- After a few client updates
    client:isDisconnected() -- true
🔗

Client:isDisconnecting()

Gets whether the client is disconnecting from the server.

Returns:

  1. boolean Whether the client is connected to the server.

Usage:

    client:disconnect()
    client:isDisconnecting() -- true
    -- After a few client updates
    client:isDisconnecting() -- false
    client:isDisconnected() -- true
🔗

Client:log(event, data)

Log an event.

Alias for Client.logger:log.

Parameters:

string event
The type of event that happened.
string data
The message to log.

Usage:

    if somethingBadHappened then
        client:log("error", "Something bad happened!")
    end
🔗

Client:on(event, callback)

Add a callback to an event.

Parameters:

string event
The event that will trigger the callback.
function callback
The callback to be triggered.

Returns:

  1. function The callback that was passed in.

Usage:

    client:on("connect", function(data)
        print("Connected to the server!")
    end)
🔗

Client:removeCallback(callback)

Remove a specific callback for an event.

Parameters:

function callback
The callback to remove.

Returns:

  1. boolean Whether or not the callback was removed.

Usage:

    local callback = client:on("chatMessage", function(message)
        print(message)
    end)
    client:removeCallback(callback)
🔗

Client:reset(client)

Forcefully disconnects the client.

The server is not notified of the disconnection.

Parameters:

Client client
The client to reset.
🔗

Client:resetSendSettings()

Reset all send options to their default values.

🔗

Client:send(event, data)

Send a message to the server.

Parameters:

string event
The event to trigger with this message.
data
The data to send.
🔗

Client:setBandwidthLimit(incoming, outgoing)

Set the incoming and outgoing bandwidth limits.

Parameters:

number incoming
The maximum incoming bandwidth in bytes.
number outgoing
The maximum outgoing bandwidth in bytes.
🔗

Client:setDefaultSendChannel(channel)

Set the default send channel for all future outgoing messages.

The initial default is 0.

Parameters:

number channel
Channel to send data on.
🔗

Client:setDefaultSendMode(mode)

Set the default send mode for all future outgoing messages.

The initial default is "reliable".

Parameters:

string mode
A valid send mode.

See also:

🔗

Client:setMaxChannels(limit)

Set the maximum number of channels.

Parameters:

number limit
The maximum number of channels allowed. If it is 0, then the maximum number of channels available on the system will be used.
🔗

Client:setMessageTimeout(timeout)

Set the timeout to wait for packets.

Parameters:

number timeout
Time to wait for incoming packets in milliseconds. The initial default is 0.
🔗

Client:setPingInterval(interval)

Set how frequently to ping the server.

The round trip time is updated each time a ping is sent. The initial default is 500ms.

Parameters:

number interval
The interval, in milliseconds.
🔗

Client:setSchema(event, schema)

Set the data schema for an event.

Schemas allow you to set a specific format that the data will be sent. If the client and server both know the format ahead of time, then the table keys do not have to be sent across the network, which saves bandwidth.

Parameters:

string event
The event to set the data schema for.
{string,...} schema
The data schema.

Usage:

    server = sock.newServer(...)
    client = sock.newClient(...)
    
    -- Without schemas
    server:send("update", {
        x = 4,
        y = 100,
        vx = -4.5,
        vy = 23.1,
        rotation = 1.4365,
    })
    client:on("update", function(data)
        -- data = {
        --    x = 4,
        --    y = 100,
        --    vx = -4.5,
        --    vy = 23.1,
        --    rotation = 1.4365,
        -- }
    end)
    
    
    -- With schemas
    client:setSchema("update", {
        "x",
        "y",
        "vx",
        "vy",
        "rotation",
    })
    -- client no longer has to send the keys, saving bandwidth
    server:send("update", {
        4,
        100,
        -4.5,
        23.1,
        1.4365,
    })
    client:on("update", function(data)
        -- data = {
        --    x = 4,
        --    y = 100,
        --    vx = -4.5,
        --    vy = 23.1,
        --    rotation = 1.4365,
        -- }
    end)
🔗

Client:setSendChannel(channel)

Set the send channel for the next outgoing message.

The channel will be reset after the next message. Channels are zero-indexed and cannot exceed the maximum number of channels allocated. The initial default is 0.

Parameters:

number channel
Channel to send data on.

Usage:

    client:setSendChannel(2) -- the third channel
    client:send("important", "The message")
🔗

Client:setSendMode(mode)

Set the send mode for the next outgoing message.

The mode will be reset after the next message is sent. The initial default is "reliable".

Parameters:

string mode
A valid send mode.

See also:

Usage:

    client:setSendMode("unreliable")
    client:send("position", {...})
🔗

Client:setSerialization(serialize, deserialize)

Set the serialization functions for sending and receiving data.

Both the client and server must share the same serialization method.

Parameters:

function serialize
The serialization function to use.
function deserialize
The deserialization function to use.

Usage:

    bitser = require "bitser" -- or any library you like
    client = sock.newClient("localhost", 22122)
    client:setSerialization(bitser.dumps, bitser.loads)
🔗

Client:setThrottle(interval, acceleration, deceleration)

Change the probability at which unreliable packets should not be dropped.

Parameters:

number interval
Interval, in milliseconds, over which to measure lowest mean RTT. (default: 5000ms)
number acceleration
Rate at which to increase the throttle probability as mean RTT declines. (default: 2)
number deceleration
Rate at which to decrease the throttle probability as mean RTT increases.
🔗

Client:setTimeout(limit, minimum, maximum)

Set the parameters for attempting to reconnect if a timeout is detected.

Parameters:

optional number limit
A factor that is multiplied with a value that based on the average round trip time to compute the timeout limit. (default: 32)
optional number minimum
Timeout value in milliseconds that a reliable packet has to be acknowledged if the variable timeout limit was exceeded. (default: 5000)
optional number maximum
Fixed timeout in milliseconds for which any packet has to be acknowledged.
🔗

Client:update()

Check for network events and handle them.

sock

🔗

newClient(serverOrAddress, port, maxChannels)

Creates a new Client instance.

Parameters:

optional string/peer serverOrAddress
Usually the IP address or hostname to connect to. It can also be an enet peer. (default: "localhost")
optional number port
Port number of the server to connect to. (default: 22122)
optional number maxChannels
Maximum channels available to send and receive data. (default: 1)

Returns:

  1. A new Client object.

See also:

Usage:

    local sock = require "sock"
    
     -- Client that will connect to localhost:22122 (by default)
    client = sock.newClient()
    
     -- Client that will connect to localhost:1234
    client = sock.newClient("localhost", 1234)
    
     -- Client that will connect to 123.45.67.89:1234, using two channels
     -- NOTE: Server must also allocate two channels!
    client = sock.newClient("123.45.67.89", 1234, 2)
🔗

newServer(address, port, maxPeers, maxChannels, inBandwidth, outBandwidth)

Creates a new Server object.

Parameters:

optional string address
Hostname or IP address to bind to. (default: "localhost")
optional number port
Port to listen to for data. (default: 22122)
optional number maxPeers
Maximum peers that can connect to the server. (default: 64)
optional number maxChannels
Maximum channels available to send and receive data. (default: 1)
optional number inBandwidth
Maximum incoming bandwidth (default: 0)
optional number outBandwidth
Maximum outgoing bandwidth (default: 0)

Returns:

  1. A new Server object.

See also:

Usage:

    local sock = require "sock"
    
     -- Local server hosted on localhost:22122 (by default)
    server = sock.newServer()
    
     -- Local server only, on port 1234
    server = sock.newServer("localhost", 1234)
    
     -- Server hosted on static IP 123.45.67.89, on port 22122
    server = sock.newServer("123.45.67.89", 22122)
    
     -- Server hosted on any IP, on port 22122
    server = sock.newServer("*", 22122)
    
     -- Limit peers to 10, channels to 2
    server = sock.newServer("*", 22122, 10, 2)
    
     -- Limit incoming/outgoing bandwidth to 1kB/s (1000 bytes/s)
    server = sock.newServer("*", 22122, 10, 2, 1000, 1000)
Generated by LDoc 1.4.3 Last updated 2017-07-24 20:20:49