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)

相关推荐
栗子叶8 小时前
两种Https正向代理的实现原理
网络协议·http·https·正向代理
玩转4G物联网1 天前
零基础玩转物联网-串口转以太网模块如何快速实现与TCP服务器通信
服务器·网络·物联网·网络协议·tcp/ip·http·fs100p
hie988941 天前
HTTP常见的请求方法、响应状态码、接口规范介绍
http
一曝十寒1 天前
那些常见的 HTTP 状态码
前端·http
什么都想学的阿超1 天前
【Redis系列 03】掌握Redis编程艺术:事务、管道与Lua脚本完全指南
redis·junit·lua
酷爱码1 天前
在 Linux 中修改 Apache HTTP Server(httpd)默认端口的完整指南
linux·http·apache
程序员祥云1 天前
https相比http的区别
网络协议·http·https
小吕学编程1 天前
HttpServletRequest常用方法
java·http
2501_915106321 天前
Flutter、React Native 项目如何搞定 iOS 上架?从构建 IPA 到上传 App Store 的实战流程全解析
websocket·网络协议·tcp/ip·http·网络安全·https·udp
编程乐学(Arfan开发工程师)1 天前
42、响应处理-【源码分析】-浏览器与PostMan内容协商完全适配
java·spring boot·后端·测试工具·lua·postman