连接时Lua套接字错误

时间:2014-05-18 17:42:24

标签: sockets lua luasocket

我试图使用Lua Socket创建一个http get:

local client = socket.connect('warm-harbor-2019.herokuapp.com',80)
if client then
    client:send("GET /get_tweets HTTP/1.0\r\n\r\n")
      s, status, partial = client:receive(1024)
    end
end

我希望 s 成为一条推文,因为我所做的得到的回报是一个。 但是我得到了:

http/1.1 404 object not found

1 个答案:

答案 0 :(得分:3)

以下是代码示例的可运行版本(显示您描述的问题):

local socket = require "socket"
local client = socket.connect('warm-harbor-2019.herokuapp.com',80)
if client then
    client:send("GET /get_tweets HTTP/1.0\r\n\r\n")
    local s, status, partial = client:receive(1024)
    print(s)
end

如果您阅读了返回的错误页面,则可以看到其标题为 Heroku |没有这样的应用程序

原因是Heroku路由器仅在提供Host标头时才有效。最简单的方法是直接使用LuaSocket的实际HTTP模块而不是TCP:

local http = require "socket.http"
local s, status, headers = http.request("http://warm-harbor-2019.herokuapp.com/get_tweets")
print(s)

如果您无法使用socket.http,则可以手动传递主机标头:

local socket = require "socket"
local client = socket.connect('warm-harbor-2019.herokuapp.com',80)
client:send("GET /get_tweets HTTP/1.0\r\nHost: warm-harbor-2019.herokuapp.com\r\n\r\n")
local s, status, partial = client:receive(1024)
print(s, status, partial)

使用我的LuaSocket版本,s将为nilstatus将为"closed"partial将包含完整的HTTP响应(包含标头等) )。