极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 9665|回复: 2

esp8266在loop中连续发包,但只有第一包服务端有返回

[复制链接]
发表于 2016-1-30 21:03:44 | 显示全部楼层 |阅读模式
如题,使用一块ESP-01,例子代码如下,http请求到服务端,服务端是没问题的,但loop中只返回一次结果,后面就connection fail了,测好久了都没办法,请大家指点

/*
*  This sketch sends data via HTTP GET requests to data.sparkfun.com service.
*
*  You need to get streamId and privateKey at data.sparkfun.com and paste them
*  below. Or just customize this script to talk to other HTTP servers.
*
*/

#include <ESP8266WiFi.h>

const char* ssid     = "your-ssid";
const char* password = "your-password";

const char* host = "data.sparkfun.com";
const char* streamId   = "....................";
const char* privateKey = "....................";

void setup() {
  Serial.begin(115200);
  delay(10);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

int value = 0;

void loop() {
  delay(5000);
  ++value;

  Serial.print("connecting to ");
  Serial.println(host);
  
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  
  // We now create a URI for the request
  String url = "/input/";
  url += streamId;
  url += "?private_key=";
  url += privateKey;
  url += "&value=";
  url += value;
  
  Serial.print("Requesting URL: ");
  Serial.println(url);
  
  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);
  
  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }
  Serial.println();
  Serial.println("closing connection");
}
回复

使用道具 举报

 楼主| 发表于 2016-1-31 10:09:58 | 显示全部楼层
之前没用<ESP8266WiFi.h>库直接写AT指令时,记得有一个关闭TCP连接的AT指令,这个库里没有相关的关闭方法,难道数据包发送完只能delay几秒等他自动断开TCP连接才能开始下一个循环?
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-1-31 10:59:09 | 显示全部楼层
为了排除服务端的问题,自建了WEB服务器,可惜也只能接到4包数据。。

Requesting URL: /test.ashx?private_key=key123456&value=4
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/7.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 31 Jan 2016 02:55:34 GMT
Connection: close
Content-Length: 7

value:4
closing connection


再向下就连接失败了。。
connecting to 139.196.12.2
connection failed
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-4-26 10:57 , Processed in 0.035822 second(s), 17 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表