套接字库,连接到网站并打印其内容。

我刚刚制作了一个简单的网站 testingtest.comyr.com(.php 文件中只包含一个回显“Hello, world!”语句),托管在 www.000webhost.com 上,我想要做的就是打印出在此处编写的内容(即“Hello, world!”文本)。 我使用的代码(请注意,我只能在我的项目中使用“socket”库):

sok1 = require("socket")

Host = "testingtest.comyr.com"
Link = "/"

sok2 = sok1.connect(Host, 80)
sok2:send("GET "..Link.." HTTP/1.0\r\n\r\n")
receive = sok2:receive('*a')
print(receive)

但是这给了我:

HTTP/1.1 302 Found
Date: Wed, 01 Oct 2014 17:03:01 GMT
Server: Apache
Location: http://error404.000webhost.com/?
Content-Length: 216
Connection: close
Connection-type: text/hmtl; charset=iso-8859-1

<!DOCUMENT HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
The document has moved here.

</body></html>
点赞
用户1442917
用户1442917

你得到了 302 状态和 Location 头部,这表明有一个重定向和一个新的 URL 跳转。由于你使用的是原始的 socket 模块,它无法处理重定向;你需要使用 socket.http 模块来处理,或者编写一些逻辑来解析响应查找 Location 头部是否有任何 3xx 状态,然后使用新的 URL 重复请求。

考虑到重定向的 URL 是 error404.000webhost.com (404 表示页面未找到),你可能在部署 PHP 页面时犯了一些错误。

如果只能使用“socket”库,类似这样的代码或可处理重定向:

sok1 = require("socket")
Host = "testingtest.comyr.com"
Link = "/"

local hosts = {}
while true do
  sok2 = sok1.connect(Host, 80)
  sok2:send("GET "..Link.." HTTP/1.1\r\nHost: "..Host.."\r\n\r\n")
  receive = sok2:receive('*a')
  -- 检查是否为重定向
  if receive:find("^HTTP/1%.%d 3%d%d") then
    local host, link = receive:match("Location: http://([^/\r\n]+)(/?[^\r\n]*)")
    if host and link and not hosts[host] then
      Host, Link = host, #link > 0 and link or "/"
      hosts[host] = true -- 跟踪重定向以避免循环
      print("redirecting to", host..link)
    end
  else
    break -- 完成
  end
end
print(#receive)

该逻辑检查循环,但仅处理重定向到http: URL(您需要检查 https 并将端口 80 更改为 443)。我还添加了 Host 头部,因为如果不添加该头部,可能无法在某些 ISP 提供商上运行,这些提供商在同一 IP 地址上托管多个域。

2014-10-02 00:03:40