lua实现http的异步回调

想用lua实现与http服务器的通信,请求一些数据会回来,默认lua.socket.http是同步的,所以想弄一个异步的方式

测试环境

  • lua 5.1

同步

以下是同步的代码,其中http.request会被阻塞住的

lua 复制代码
local function send_request()
    local res, code, response_headers = http.request(
        "http://www.lua.org/",
        "POST",
        "name=Lua&age=100",
        {["Content-Type"] = "application/x-www-form-urlencoded"}
    )
    print("code = ", code)
end
send_request();

输出结果:

lua 复制代码
F:\study\lua\fragmentary> lua "f:\study\lua\fragmentary\socket\client.lua"
code =  200

如果每次执行一次请求,就卡住我们逻辑的Tick,那整个客户端就卡在那里了。所以,我需要非阻塞的用法。也就是执行请求之后,不用等http服务器返回结果,而是继续向下执行。我主动监听,有返回了,再回调我的逻辑。

异步

参考[2],给出了一定的思路,但是我是看到GPT给的结果,代码都详细列出来了,直呼牛皮啊!

lua 复制代码
    local host = "www.baidu.com"
    local path = "";
    local data = [[name=Lua&age=100]]
    local port = 80;
    local con = assert(socket.connect(host, port))
    self.Conn:settimeout(0)
    
    local request = string.format("POST /%s HTTP/1.0\r\nHost: %s\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: %d\r\n\r\n%s",path, host, #data, data)

    con:send(request)

    local response = ""
    while true do
        local chunk, status, partial = con:receive(1024)
        response = response .. (chunk or partial)
        print("status = ", status);
        if status == "closed" then
            break;
        end
    end

输出:

复制代码
status =        nil
status =        nil
status =        closed

小结:

  • 1.主要是用tcp连接,用非阻塞的方式去实现
  • 2.自己通过receive接口获取数据

参考

1\][socket.http](https://lunarmodules.github.io/luasocket/http.html) \[2\][Non-Preemptive Multithreading](https://www.lua.org/pil/9.4.html)

相关推荐
Mr_Xuhhh5 小时前
NAT、代理服务、内网穿透
网络·网络协议·http·https·udp·智能路由器
weisian1511 天前
HTTP协议-3-HTTP/2是如何维持长连接的?
网络·网络协议·http
xie_pin_an1 天前
网络原理与编程实战:从 TCP/IP 到 HTTP/HTTPS
网络·tcp/ip·http
teeeeeeemo1 天前
如何做HTTP优化
前端·网络·笔记·网络协议·http
weisian1511 天前
HTTP协议-4-浏览器是怎么抉择HTTP版本的?
网络·网络协议·http
水冗水孚1 天前
图文并茂讲解nginx中http升级https(部署SSL证书)知识点总结
nginx·http·https
athink_cn2 天前
HTTP/2新型漏洞“MadeYouReset“曝光:可发动大规模DoS攻击
网络·网络协议·安全·http·网络安全
网络研究院2 天前
新的“MadeYouReset”方法利用 HTTP/2 进行隐秘的 DoS 攻击
网络·网络协议·安全·http·攻击·漏洞
玩转以太网3 天前
基于W55MH32Q-EVB 实现 HTTP 服务器配置 OLED 滚动显示信息
服务器·网络协议·http
清源妙木真菌3 天前
应用层协议——HTTP
网络·网络协议·http