如何以几秒钟的延迟间隔向客户端发送http响应

时间:2019-12-09 11:18:44

标签: http server lua client httpserver

我正在研究lua,这对我来说是很新的东西,我在向客户端发送http响应的过程中遇到了一些延迟。

我想连续发送http响应给客户端,响应之间间隔几秒钟...

这里我具有以下功能,

我在客户端每2秒需要http响应,但是在客户端10秒后我得到响应。 我使用cqueues.sleep产生了当前线程一秒钟。

local httpserver = require('turbo.httpserver')
local httputil = require('turbo.httputil')
local ioloop = require('turbo.ioloop')
local ioloop_instance = ioloop.instance()
local turbo = require("turbo")
local header = turbo.httputil.HTTPHeaders()
local cqueues = require "cqueues"
function handle_request(request)
     -- This is the callback function for HTTPServer.
    -- It will be called with a HTTPRequest class instance for every request
    -- issued to the server.
        local buf
        local req_headers = assert(request.headers)
        local path = req_headers["url"]
         print("url path", path)
        --print("start",start)
        --print("METHOD",request:get_method())
        if path =="/event-stream" then
                print("elseif condition success")
                header:add("Content-Type", "text/event-stream")
                header:add("Cache-Control", "no-cache")
                header:add("Connection", "Keep-alive")
                header:set_status_code(200)
                header:set_version("HTTP/1.1")
                local hdr_msg = header:stringify_as_response()
                local buf = hdr_msg .. "\r\n"
                request:write(buf)
                local i =1
                while i <= 5 do
                        print("sending Message to client *** " .. i)
                        request:write("id: UniqueID\n")
                        request:write("event: add\n")
                        request:write("data: " .. i .. "\n\n")
                        i = i+1
                        cqueues.sleep(2) -- yield the current thread for a second.
                end
        end
end

http_server = httpserver.HTTPServer:new(handle_request)
http_server:listen(8000)
ioloop_instance:start()

实际输出:

-延迟10秒后---

id:唯一ID 事件:添加 数据:1

id:唯一ID 事件:添加 数据:2

id:唯一ID 事件:添加 数据:3

id:唯一ID 事件:添加 数据:4

id:唯一ID 事件:添加 数据:5

预期输出:

id:唯一ID 事件:添加 数据:1

--- 2秒延迟---

id:唯一ID 事件:添加 数据:2

--- 2秒延迟---

id:唯一ID 事件:添加 数据:3

--- 2秒延迟---

id:唯一ID 事件:添加 数据:4

--- 2秒延迟---

id:唯一ID 事件:添加 数据:5

0 个答案:

没有答案