7

Lua实现http的异步回调

 1 year ago
source link: http://pkxpp.github.io/2023/08/13/lua%E5%AE%9E%E7%8E%B0http%E7%9A%84%E5%BC%82%E6%AD%A5%E5%9B%9E%E8%B0%83/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Lua实现http的异步回调


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

  • lua 5.1

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

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();

输出结果:

F:\study\lua\fragmentary> lua "f:\study\lua\fragmentary\socket\client.lua"
code =  200

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

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

    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

[2]Non-Preemptive Multithreading


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK