luasocket reveive and send at the same time

luasocket reveive and send at the same time

原文出处:http://www.qixing318.com/article/use-lua-extension-libraries-luasocket-cases.html

稍加修改,即可用在自己的项目上。

server lua 

-- server.lua
local socket = require("socket")
 
local host = "127.0.0.1"
local port = "12345"
local server = assert(socket.bind(host, port, 1024))
server:settimeout(0)
local client_tab = {}
local conn_count = 0
 
print("Server Start " .. host .. ":" .. port) 
 
while 1 do
    local conn = server:accept()
    if conn then
        conn_count = conn_count + 1
        client_tab[conn_count] = conn
        print("A client successfully connect!") 
    end
  
    for conn_count, client in pairs(client_tab) do
        local recvt, sendt, status = socket.select({client}, nil, 1)
        if #recvt > 0 then
            local receive, receive_status = client:receive()
            if receive_status ~= "closed" then
                if receive then
                    assert(client:send("Client " .. conn_count .. " Send : "))
                    assert(client:send(receive .. "\n"))
                    print("Receive Client " .. conn_count .. " : ", receive)   
                end
            else
                table.remove(client_tab, conn_count) 
                client:close() 
                print("Client " .. conn_count .. " disconnect!") 
            end
        end
         
    end
end

client lua

-- client.lua
local socket = require("socket")
 
local host = "127.0.0.1"
local port = 12345
local sock = assert(socket.connect(host, port))
sock:settimeout(0)
  
print("Press enter after input something:")
 
local input, recvt, sendt, status
while true do
  --  input = io.read()
    input = "Testing"
    if #input > 0 then
        assert(sock:send(input .. "\n"))
    end
     
    recvt, sendt, status = socket.select({sock}, nil, 1)
    while #recvt > 0 do
        local response, receive_status = sock:receive()
        if receive_status ~= "closed" then
            if response then
                print(response)
                recvt, sendt, status = socket.select({sock}, nil, 1)
            end
        else
            break
        end
    end
end

发表评论

电子邮件地址不会被公开。 必填项已用*标注