2

我的问题是关于 lua 套接字,说我有一个聊天,我想为那个聊天制作一个机器人。但是聊天有多个房间,所有房间都在不同的服务器上,这些房间由一个称为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

现在,当所有运行它只接收来自第一个房间的数据时,我不知道如何解决这个问题

4

1 回答 1

1

尝试创建一系列连接。连接房间的地图也可能有用。例子:

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](这没有意义,因为连接是一个数组,而不是一个映射)。

于 2014-03-25T21:54:15.627 回答