-- @runtimes lua54 --- 演示:cosocket 风格的非阻塞请求(stub)。 local M = {} local function fetch(socket, host) socket:connect(host, 80) socket:send("GET / HTTP/1.1\r\nHost: " .. host .. "\r\n\r\n") local response = socket:receive("*a") socket:close() return response end --- @return table { bytes = integer, connected = boolean } function M.run(log) log = log or print local connected = false local socket = { connect = function(_, host, port) assert(host == "example.com" and port == 80) connected = true end, send = function() end, receive = function() return "HTTP/1.1 200 OK\r\n\r\nok" end, close = function() end, } local response = fetch(socket, "example.com") log(("bytes=%d connected=%s"):format(#response, tostring(connected))) return { bytes = #response, connected = connected } end if not ... then M.run() end return M