Working with LuaSocket, this code works:
local socket = require'socket'
local server = socket.bind('*',51423)
local client = server:accept()
but this code fails:
local socket = require 'socket'
local server = socket.tcp()
server:bind('*',51423)
local client = server:accept()
--> lua: /tmp/server.lua:4: calling 'accept' on bad self (tcp{server} expected, got userdata)
Yet the documentation for TCP bind implies that the latter should work, stating:
"Note: The function socket.bind is available and is a shortcut for the creation of server sockets."
How can I convert a generic "master" object into a server?
The motivation for this is the desire to add a timeout on the bind operation itself:
local socket = require'socket'
local server = socket.tcp()
server:settimeout(2/1000) -- Only wait 2ms when attempting to bind
server:bind('*',51423)
The answer is at the top of the same documentation page (oops):
"A master object can be transformed into a server … with the method
listen
(after a call tobind
)"
It would seem that s = socket.bind(…)
is actually equivalent to:
s = socket.tcp()
s:bind(…)
s:listen(32)
I'm not sure why they are split into two functions, but modifying the code to add listen()
causes it to work:
local socket = require 'socket'
local server = socket.tcp()
server:bind('*',51423)
server:listen(32)
local client = server:accept()