Lua处理多个连接的套接字

我的问题是关于 Lua sockets 的,假设我有一个聊天室,我想要为这个聊天室 创建一个机器人。但是这个聊天室有多个房间,所有房间在不同的服务器上并由一个名为 getServer 的函数计算出来。

连接函数应该是这样的:

function connect(room)
   con = socket.tcp()
   con:connect(getServer(room), port)
   con:settimeout(0)
   con:setoption('keepalive', true)
   con:send('auth' .. room)

循环函数应该是这样的:

function main()
   while true do
     rect, r, st = socket.select({con}, nil, 0.2)
     if (rect[con] ~= nil) then
        resp, err, part = con:receive("*l")
        if not( resp == nil) then
            self.events(resp)
 end
    end
       end
          end

现在当所有这些运行时,它只从第一个房间接收数据,我不知道该如何修复它。

点赞
用户869951
用户869951

尝试创建一个连接数组。房间连接图也可能会有用。例如:

local connections = {}
local roomConnMap = {}

function connect(room)
   local con = socket.tcp()
   con:connect(getServer(room), port)
   con:settimeout(0)
   con:setoption('keepalive', true)
   con:send('auth' .. room)

   table.insert(connections, con)
   roomConnMap[room] = con
end

function main()
   while true do
     local rect, r, st = socket.select(connections, nil, 0.2)
     for i, con in ipairs(rect) do
        resp, err, part = con:receive("*l")
        if resp ~= nil then
            self.events(resp)
        end
     end
   end
end

请注意,rect是一组已找到要读取数据的连接项的数组。因此,在 for i,con 循环中,con 是连接对象,不要使用 connections[con](这没有意义,因为 connections 是一个数组,而不是一个映射)。

2014-03-25 21:54:15