Lua 的一个小demo?教一下,感激不尽!!

Lua 用协程(coroutine)实现

  • 一个server端可以等待多个client端连接。
  • 分别用Lua实现 server、client
  • 有源码(只需要最基本的回显功能)

--lua的TCP通信发送字符串末尾必须添加\n
--server
socket = require("socket")  --调用socket包
ip = "192.168.3.184" --程序设置自己为Server端,设置自己的ip地址
port = 8080 --设置端口
 
server = assert(socket.bind(ip, port))  --按照上面的参数开启服务器
 
ack = "ack\n"
while 1 do
    print("server: waiting for client connection...")
    control = assert(server:accept())   --等待客户端的连接,因此这个程序只能同时连接一个TCP客户端设备
    while 1 do
        command, status = control:receive() --等待字符信号发送过来
        if command == "closed" then
            break
        end
        if command ~= nil then
            print(command)
            control:send(ack)
        end
    end
end
--lua的TCP通信发送字符串末尾必须添加\n
--client
socket = require("socket")  --调用socket包
ip = "192.168.3.184"    --程序设置要了解的server端的ip地址
port = 8080 --设置端口
 
c = assert(socket.connect(ip, port))    --根据上边的参数连接server端,若未连接上直接报错
 
c:send("GET\n") --首先发送一个信号
 
while 1 do
    s, status, partial = c:receive()    --等待服务器发送过来的信号
    print(s)
    if status == "closed" then 
        break
    end
    str_send = io.read()    --等待输入要发送出去的信号
    str_send = str_send..'\n'
    c:send(str_send)
end
 
c:close()


参考链接,期望对你有所帮助:https://blog.csdn.net/lby13951652332/article/details/107712426