【问题标题】:lua socket handling multiple connectionslua套接字处理多个连接
【发布时间】:2014-03-27 05:41:35
【问题描述】:

我的问题是关于 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

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

【问题讨论】:

  • 显示您为每个房间调用 connect() 的代码,而主要的,不要显示片段。并修复坏的缩进。
  • 我会将它链接到 github 存储库,因为文件很大;(link Github[link] 只需添加 socket.select() 就可以了
  • 这不是我的意思。显示调用connect(room) 的代码和调用main() 的代码。您附加的链接不包含这些。
  • 对不起,main() 函数是 ch_handler 函数,connect 在 ch_init 内部调用,ch_init 函数在 example.lua 中调用 link example.lua
  • 您需要创建一个SSSCE。代码太多。也许是con,它是ch_connect中的一个全局集合,然后在ch_handler中使用,但是每个连接都会用最新的连接覆盖引用?

标签: lua luasocket


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

【讨论】:

  • 我试过这个,首先它说尝试调用一个表值,所以我做了for con in ipairs(rect) do,它从来没有真正连接到房间
  • 不完全是当我使用您的代码运行时,它连接到房间但没有收到数据,然后我做到了,for con in ipairs(rect) do resp, err, part = connection[con]:receive('*l'),因为据我所知。 socket.select() 使用一个数组并且该数组保存每个连接,选择作业是等待接收数据,然后将该连接输出为一个数字,例如连接保存两个连接 r1、r2。当 r1 接收数据时 con 值为 1,当 r2 接收数据时 con 值为 2 对吗?但是当它确实获取数据时,它会输出错误。
  • 说,attempt to index field '?' (a nil value) 并且该错误来自receive()
  • @user3103366 那是因为我在我输入的代码中有几个错误。看看这是否更好。您评论中的代码缺少i,我将其放入更新的答案中,并解释为什么不使用connection[con]。注意我使用了connections 而不是connection,因为它是一个数组。希望它现在有效。
  • 非常感谢,现在可以使用了。有趣的是我之前尝试过一次 for 循环,但我忘记使用 ipairs 而不是对这个问题已解决
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 2010-12-07
  • 2013-11-18
  • 1970-01-01
  • 2012-08-27
相关资源
最近更新 更多