我写了一个应用程序,Android
它实现了向Volley
服务器发送简单的请求(使用)。服务器位于 NodeMCU (ESP8266) 微控制器上,以Lua
. 问题是,发送请求后,应用程序并不总是能够打印响应。如果地址是例如“ http://www.google.com ”,它会正确发送请求并接收并显示响应,但如果它是下面代码中的地址 - 它会正确发送请求(服务器做出反应)但没有( ?) 接收响应(不显示它,显示:“那没有用!”)。您有什么想法,我该如何解决并打印回复?
Android(负责发送请求的部分):
buttonSynchro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Instantiate the RequestQueue.
String url = "http://192.168.1.12/";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
testTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
testTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(SettingsActivity.this);
queue.add(stringRequest);
}
});
NodeMCU,Lua:
station_cfg={}
station_cfg.ssid="Dom"
station_cfg.pwd="lalala"
wifi.sta.config(station_cfg)
function receive(conn, request)
print(request)
print()
local buf = "";
buf = buf.."<!doctype html><html>";
buf = buf.."<h1> ESP8266 Web Server</h1>";
buf = buf.."</html>";
conn:send(buf);
conn:on("sent", function(sck) sck:close() end);
collectgarbage();
end
function connection(conn)
conn:on("receive", receive)
end
srv=net.createServer(net.TCP, 30)
srv:listen(80, connection)
nPn 的代码适用于某些用户代理(macOS 上的 Chrome/Firfox/curl/wget),但不适用于其他用户代理(macOS 和 iOS 上的 Safari,iOS 上的 Firefox Klar)。这可能是由于缺少 HTTP 标头。
我建议您坚持我们在https://nodemcu.readthedocs.io/en/latest/en/modules/net/#netsocketsend文档中的示例。
srv = net.createServer(net.TCP)
function receiver(sck, data)
print(data)
print()
-- if you're sending back HTML over HTTP you'll want something like this instead
local response = {"HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n"}
response[#response + 1] = "<!doctype html><html>"
response[#response + 1] = "<h1> ESP8266 Web Server</h1>"
response[#response + 1] = "</html>"
-- sends and removes the first element from the 'response' table
local function send(localSocket)
if #response > 0 then
localSocket:send(table.remove(response, 1))
else
localSocket:close()
response = nil
end
end
-- triggers the send() function again once the first chunk of data was sent
sck:on("sent", send)
send(sck)
end
srv:listen(80, function(conn)
conn:on("receive", receiver)
end)
此外,您的代码(以及与此相关的 nPn)假设 WiFi 在不该可用的地方可用。
wifi.sta.config(station_cfg)
(使用 auto-connect=true)并且wifi.stat.connect
是异步的,因此是非阻塞的 - 与许多其他 NodeMCU API 一样。因此,您应该将上述代码放入一个函数中,并且只有在设备连接到 AP 并获得 IP 后才调用它。您可以通过例如STA_GOT_IP
使用 WiFi 事件监视器注册事件回调来实现。您会在https://nodemcu.readthedocs.io/en/latest/en/upload/#initlua找到一个非常详细的启动序列示例,该示例侦听所有 WiFi 事件。对于初学者,您可能想要修剪它并只收听获得的 IP。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句