将消息发送到TCP服务器中的处理程序功能光纤

问题描述

如果从tcp_server()模块传递到socket的处理函数以光纤运行,是否有可能通过fiber.channel与每个tcp_connection通信?

解决方法

是的。

#!/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()

当然,这个代码片段虽然还不够完善,但我希望它能帮助您完成工作。