How to specify timeout on a socket request

I have the following LUA script in an event:

local socket = require(“socket”)
host = “192.168.0.3”
client = assert(socket.connect(host, 5150))
client:send(“@movie\r”)
client:close()

This sends text to a node.js script which I have running on a PC at that address (just a TCP server).

All works OK when that server is on, but when I turn it off the LUA script waits for about a minute before it continues with the other actions (such as turning lights one).

It is obviously pending a timeout.

What I’d like to do is to set the timeout to about 3 seconds so that it gives up quickly if the server/PC isnt on but I cant find out how to set it.

The doc will help:
LuaSocket: TCP/IP support

Thanks for that.

I have tried many different permutations and it still waits for about 3 mins if the server isnt on with this code:

local socket = require("socket")
host = "192.168.0.3"
local client = socket.connect(host, 5150)
if (client == "nil" or client == nil) then
  luup.log("Connection to pc failed")
else
  luup.log("Connection to PC OK")
   client:settimeout(3)
   client:send("@movie\r")
   client:close()
end

I have also tried this:

local socket = require("socket")
host = "192.168.0.3"
local client = socket.connect(host, 5150)
client:settimeout(3)
client:send("@movie\r")
client:close()

although with that I would guess the client object isnt set so would probably throw an error when trying to use it.

I wonder if the timeout is occuring on the initial socket.connect which my setting on the client wouldnt affect but I have no idea how to set the timeout on that.

Anbody any ideas?

You need to used socket.tcp to get the handle, then set the timeout on it, then do a connect on the resulting handle.

There are a few examples on the web if you search for “luasocket timeout”

Great thanks.

This now works for when the server is either running or is not without any delays:

local socket = require("socket")
host = "192.168.0.3"
local tcp = assert(socket.tcp())
if( tcp ~= "nil" and tcp ~= nill) then
  tcp:settimeout(1)
  tcp:connect(host, 5150)
  tcp:send("@movie\r")
  tcp:close()
end

Thanks for your help!