我正试图从ESP8266和测试服务器(如www.httpbin.org)建立连接以获取一些数据。我一直有问题。 我使用的是一个非常简单的代码(不包括与本地WiFi的明显连接),如下所示:
net.dns.setdnsserver("8.8.8.8",1)
net.dns.resolve("httpbin.org", function(server_ip)
if (server_ip == nil) then print("DNS fail!") else
print(server_ip)
conn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload)
print('\nReceived\n')
print(payload)
end )
conn:on("connection", function(conn, payload)
print('\nConnected')
conn:send("HTTP/1.1\r\n"
.."Host: httpbin.org/get\r\n"
.."Connection: keep-alive\r\n"
.."Accept: */*\r\n\r\n")
end)
conn:connect(80, server_ip)
end
end)
结果是print(server_ip)返回
userdata: 3fff1b80
连接挂起(我从未打印任何消息)。我究竟做错了什么?感谢。
答案 0 :(得分:0)
你快到了。试试这个:
net.dns.setdnsserver("8.8.8.8", 1)
net.dns.resolve("httpbin.org", function(sk, server_ip)
if (server_ip == nil) then print("DNS fail!") else
print(server_ip)
conn = net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload)
print("Received: " .. payload)
end)
conn:on("connection", function(conn, payload)
print("Connected")
conn:send("GET /get HTTP/1.1\r\n"
.. "Host: httpbin.org\r\n"
.. "Connection: keep-alive\r\n"
.. "Accept: */*\r\n\r\n")
end)
conn:connect(80, server_ip)
end
end)
我改变了两件事:
net.dns.resolve
的回调具有 2 参数(套接字和IP地址)host
真的只是主持人GET /get HTTP/1.1
当然,您也可以将其删除至:
conn = net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload)
print("Received: " .. payload)
end)
conn:on("connection", function(conn, payload)
print("Connected")
conn:send("GET /get HTTP/1.1\r\n"
.. "Host: httpbin.org\r\n"
.. "Connection: keep-alive\r\n"
.. "Accept: */*\r\n\r\n")
end)
conn:connect(80, "httpbin.org")