2014-03-24 86 views
2

我的問題是關於lua套接字,說我有一個聊天,我想爲這個聊天做一個bot。但聊天了所有對不同模式的服務器多間客房由一個名爲getServer 函數計算的連接功能看起來像這樣lua socket處理多個連接

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 

現在時所有運行它只接收來自第一個房間的數據,我不知道如何解決這個問題

+0

顯示您爲每個房間調用connect()的代碼,而main顯示不顯示的部分。並修復不好的縮進。 – Schollii

+0

我會鏈接到一個github回購,因爲該文件是大;([鏈接Github](https://github.com/ericraio/ch.lua/blob/master/ch.lua)[鏈接]只是添加socket.select()和那幾乎是我得到的 – user3103366

+0

這不是我的意思。顯示調用'connect(room)'和調用'main()'的代碼的代碼。那些。 – Schollii

回答

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](這沒有意義,因爲連接是一個數組,而不是映射)。

+0

我試過這個,首先它說試圖調用一個表值,所以我沒有'對con在ipairs(矩形)做',它從來沒有實際連接到房間 – user3103366

+0

大聲笑這就是我的錯誤我忘了發送字節爲以及 – user3103366

+0

@ user3103366那麼它解決了你的問題? – Schollii