目录

Lua Socket in Win

Lua Socket在Windows平台下的使用

在上一篇博文中介绍了VS2015+Lua5.1.5环境的搭建,最后介绍了Lua解释器的创建。本文将继续介绍Lua的一个比较实用的拓展库Lua Socket在Windows下平台的使用。在网上查看了许多关于Lua Socket的安装,发现大部分都是在Linux下的安装,关于在Windows平台下的使用说明很少,而且发现问题挺多。本文将介绍一个极其简单的方式介绍Lua Socket在Windows下的安装使用,亲测可用。

1、首先下载编译好后的Lua Socket库:

http://files.luaforge.net/releases/luasocket/luasocket/luasocket-2.0.2

选择:

https://cdn.jsdelivr.net/gh/xinqinew/pic@main/img/SouthEast.png

2、(关键)解压后将socket目录下的core.dll重命名为socket.dll,并将文件夹lua及socket.dll拷贝到LuaTest生成目录下(具体可参考上一篇博文

https://cdn.jsdelivr.net/gh/xinqinew/pic@main/img/SouthEast-20220502001202996.png

3、修改main.lua:

 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
-- 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("服务器开启 " .. 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

编译运行:

https://cdn.jsdelivr.net/gh/xinqinew/pic@main/img/SouthEast-20220502001213644.png

此外,补充一个客户端程序:

 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
26
27
28
29
30
-- 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()
    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