关于luasocket:处理多个连接的lua套接字

lua socket handling multiple connections

我的问题是关于lua套接字的,说我有一个聊天室,并且我想为该聊天室制作一个机器人。但是聊天在不同的服务器上都有多个聊天室,这些聊天室是由称为getServer的函数计算的
连接函数看起来像这样

1
2
3
4
5
6
function connect(room)
   con = socket.tcp()
   con:connect(getServer(room), port)
   con:settimeout(0)
   con:setoption('keepalive', true)
   con:send('auth' .. room)

及其循环功能将是

1
2
3
4
5
6
7
8
9
10
11
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

现在,所有运行时它仅从第一个房间接收数据,我不知道如何解决该问题


尝试创建连接数组。将房间映射为连接也可能很有用。示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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](这没有意义,因为连接是数组而不是映射)。