This took me a while to work out but here is a example of how to do send
and receive on a single socket connection without blocking. I have a real time
game server I wrote using the guts (ioloop portion) from the facebook python tornado
web server. This is the snippet of code that I use to talk to it send, rcv on the same
socket connection without blocking the app. If anyone tries doing it with coroutines good
luck to ya I could not make that work reliably.
[lua]require “socket”
conn = socket.connect(“127.0.0.1”,8000)
_msgsendtable = {}
–send
function _mrcv(connection,rcallback)
connection:settimeout(0)
local s, status = connection:receive()
if s ~= nil then
rcallback(s)
end
end
–receive
function _msend(connection)
local cnt = #_msgsendtable
if cnt > 0 then
for key,msg in pairs(_msgsendtable) do
if msg ~= nil then
connection:send(msg … “\r\n”)
end
_msgsendtable[key] = nil
end
end
end
–send function queues data for transmission
function msgsend(data)
table.insert(_msgsendtable,data)
end
–receive data is passed to this callback
function message_recvd(data)
print(data)
end
–setup timers to handle update and receive
timer.performWithDelay(1,function() _mrcv(conn,message_recvd) end,0)
timer.performWithDelay(1,function() _msend(conn) end,0)
–test send json messages
msgsend("[“m”,“br”,“a”]")
msgsend("[“m”,“br”,“b”]")
msgsend("[“m”,“br”,“c”]")
msgsend("[“m”,“br”,“d”]")
msgsend("[“m”,“br”,“e”]") [/lua]
There is no error trapping or anything of that sort in this routine that is a exercise left to the reader. I did test this some by placing this code snippet in “Tilt Monster” broadcasting accelerometer data to a few connected clients and it did not seem to mess with the games performance at all. [import]uid: 14451 topic_id: 10897 reply_id: 310897[/import]