2
votes

my question is about lua sockets, say I have a chat and I want to make a bot for that chat. But the chat has multiple rooms all on defferent servers that are calculated by a function called getServer the connect function would look like this

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

and the function to loop it would be

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

now when all that runs it only receives data from the first room and I dunno how to fix that

1
Show the code where you call connect() for each rooms, and the main, don't show pieces. And fix the bad indentation. - Oliver
I'll link it to a github repo because the file is to big ;( link Github[link] just add the socket.select() and thats pretty much what i got - user3103366
This is not what I meant. Show the code that calls connect(room) and the code that calls main(). The link you attached contains neither of those. - Oliver
I'm sorry, the main() function is the ch_handler function and the connect is called inside ch_init and the ch_init function is called in example.lua here link example.lua - user3103366
You need to create a SSSCE. Too much code. Perhaps the con, which is a global set in ch_connect and then used in ch_handler, but every connection will overwrite the reference with latest connection? - Oliver

1 Answers

1
votes

Try creating an array of connections. A map of room to connections might also be useful. Example:

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

Note that rect is an array of items found connections for which there is data to be read. So in the for i,con loop the con is the connection object, do not use connections[con] (this doesn't make sense because connections is an array, not a map).