Reputation: 334
If handler function passed to tcp_server()
from socket
module runs as fiber is there possibility to communicate with each tcp_connection by fiber.channel
?
Upvotes: 0
Views: 144
Reputation: 323
Yes, it is.
#!/usr/bin/tarantool
local fiber = require('fiber')
local socket = require('socket')
local clients = {}
function rc_handle(s)
-- You can save socket reference in some table
clients[s] = true
-- You can create a channel
-- I recommend attaching it to the socket
-- so it'll be esier to collect garbage
s.channel = fiber.channel()
-- You can also get the reference to the handling fiber.
-- It'll help you to tell alive clients from dead ones
s.fiber = fiber.self()
s:write(string.format('Message for %s:%s: %s',
s:peer().host, s:peer().port, s.channel:get()
))
-- Don't forget to unref the client if it's done manually
-- Or you could make clients table a weak table.
clients[s] = nil
end
server = socket.tcp_server('127.0.0.1', 3003, {
name = 'srv',
handler = rc_handle,
})
function greet_all(msg)
-- So you can broadcast your message to all the clients
for s, _ in pairs(clients) do
s.channel:put(msg)
end
end
require('console').start()
Of course, this snippet if far from being perfect, but I hope it'll help you to get the work done.
Upvotes: 1