当前位置: 首页>>代码示例>>C++>>正文


C++ WiFiClient::flush方法代码示例

本文整理汇总了C++中WiFiClient::flush方法的典型用法代码示例。如果您正苦于以下问题:C++ WiFiClient::flush方法的具体用法?C++ WiFiClient::flush怎么用?C++ WiFiClient::flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在WiFiClient的用法示例。


在下文中一共展示了WiFiClient::flush方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: loop

void loop() {
  // NETWORKING
  // TODO FIGURE OUT WHETHRE THIS IS BLOCKING
  WiFiClient client = server.available();
  if (!client) return; // TODO CONTINUE LOOPING
  
  int timeout = COMM_TIMEOUT; // TODO LESS BUSY WAIT?
  logMsg("New client");
  while(!client.available() && --timeout>0) {
    delay(1);
  }
  if (timeout <= 0) {
    logMsg("TIMEOUT");
    client.flush();
    return;
  }
  
  // GET MSG
  // TODO FIGURE OUT WHY DOESN'T WORK DIRECTLY
  String str = client.readStringUntil(0);  
  client.flush();
  logMsg(String("Got message [") + str + "]");
  
  // SEND REPLY
  client.print(processRequest(str).toString());
  delay(1);
  logMsg("Client disonnected");
}
开发者ID:eggyolkmedia,项目名称:wifibox,代码行数:28,代码来源:box.cpp

示例2: Iotfy_getdata

String Iotfy_getdata(int no_of_bytes, int timeout)
{
  int ctr=0;
  int pt=millis()/1000;
  String data="";
  data.reserve(no_of_bytes);
  while(1)
  {
    if(client.available())
    {
      char c=client.read();
      data+=c;
      Serial.print(c);
      ctr++;
      if(ctr==no_of_bytes)
        break;
    }      
    else
    {
      if(millis()/1000-pt>timeout)
      {
        pt=millis()/1000;
        break;    
      } 
    }
  }
  Serial.println("calling disconnect");
  client.flush();
  client.stop();
     
  return data;
}
开发者ID:Iotfy,项目名称:iotfy-libs,代码行数:32,代码来源:iotfy.cpp

示例3: transmitTele

void transmitTele()
{
  Serial.println("tele"); 
  
  while(!alreadyConnectedTele)
  {
    //attempt to save a client connecting to the server
    teleClient = teleServer.available();
    
    //if a client is connected, begin communication
    if (teleClient) {
      if (!alreadyConnectedTele) {
        // clead out the input buffer:
        teleClient.flush();
        Serial.println("We have a new client");
        alreadyConnectedTele = true;
        
      }
    }
  }
  
    for(int i = 0; i < 20; i++)
    {
      if (teleClient.available() > 0) {
        // read the bytes incoming from the client:
        char thisChar = teleClient.read();
        // echo the bytes back to the client:
        
        if(thisChar == '1')
          teleServer.println(curSpeedKn * KNOTS_TO_MPS);
          
        if(thisChar == '2')  
          teleServer.println(pollPing());
          
        if(thisChar == '3')
          teleServer.println(distToTar());
          
        if(thisChar == '4')
          teleServer.println(curLat);
        
        if(thisChar == '5')
          teleServer.println(curLon);
        
        if(thisChar == '6')
          teleServer.println(curHead);
        
        
        // echo the bytes to the server as well:
        Serial.println(thisChar);
      }
    }
    
    
    
  
}
开发者ID:DynamicBrute,项目名称:SARSRover,代码行数:56,代码来源:RoverFi.cpp

示例4: APServer

void APServer(){
    WiFiClient client = server.available();  // Check if a client has connected
    if (!client) {
        return;
    }
    Serial.println("");
    Serial.println("New client");

    // Wait for data from client to become available
    while (client.connected() && !client.available()) {
      delay(1);
    }
    
    // Read the first line of HTTP request
    String req = client.readStringUntil('\r');
    Serial.println(req);
    String s;
    String gsid;
    String gpwd;
    //if the form has been submitted
    if(req.indexOf("ssid")!=-1){
      //TODO Make this a POST request
      //I'm basically hoping they're being nice
      int x = req.indexOf("ssid")+5;
      gsid = req.substring(x,req.indexOf("&",x));
      x = req.indexOf("pwd")+4;
      gpwd = req.substring(x,req.indexOf(" ",x));
      s = gsid;
      saveWifiConfig(gsid,gpwd);
      Serial.print("Restarting");
      client.print("Thanks! Restarting to new configuration");
      client.flush();
      ESP.restart();
    }
    else{
    s =  "<h1>Welcome to your ESP</h1><form action='/' method='get'><table><tr><td>SSID</td><td><input type='text' name='ssid'></td></tr><tr><td>Password</td><td><input type='text' name='pwd'></td><tr><td /><td><input type='submit' value='Submit'></td></tr></form>";
    client.print(s);
    }
    client.flush();
    delay(1);
    //Serial.println("Client disonnected");
}
开发者ID:TheWat,项目名称:Arduino,代码行数:42,代码来源:APmode.cpp

示例5: waitForTarget

void waitForTarget()
{
  //define a client object to connect to the server
  WiFiClient mainClient;
  
  //wait for a client to connect to the server
  while(!alreadyConnectedMain)
  {
    //attempt to save a client connecting to the server
    mainClient = mainServer.available();
    
    //if a client is connected, begin communication
    if (mainClient) {
      if (!alreadyConnectedMain) {
        // clead out the input buffer:
        mainClient.flush();
        Serial.println("We have a new client");
        debugServer.println("We have a new client");
        mainClient.println("Hello, client!");
        alreadyConnectedMain = true;
        
      }
    }
    
    delay(100);
    
    delay(100);
  }
  Serial.println("writing");
  debugClient.println("writing");
  
  //mainServer.println("ready");
  delay(1000);
  
  //Strings to read in latitude and longitude from the client
  char lat[50] = "";
  char lon[50] = "";
  
  int ind = 0;
  
  //Wait for input to be on the buffer
  while(!mainClient.available());
  
  char destNum = '0';
  
  while(!(destNum == '1' || destNum == '2' || destNum == '3'))
  {
    destNum = mainClient.read();
    Serial.println(destNum);
  }
  
  if(destNum == '1')
  {
    tarLat = LAT1;
    tarLon = LON1;
  }
  if(destNum == '2')
  {
    tarLat = LAT2;
    tarLon = LON2;
  }
  if(destNum == '3')
  {
    tarLat = LAT3;
    tarLon = LON3;
  }
  
  /*
  //Read in characters from the input buffer until a new line character is reached
  //this will be the latitude
  while(mainClient.available())
    {
      char c = mainClient.read();
      lat[ind] = c;
      
      if(c == '\n')
      {
        lat[ind] = NULL;
        break;
      }
      
      ind++; 
    }
  
  ind = 0;
  
  //Read in characters from the input buffer until a new line character is reached
  //this will be the longitude
  while(mainClient.available())
    {
      char c = mainClient.read();
      lon[ind] = c;
      
      if(c == '\n')
      {
        lon[ind] = NULL;
        break;
      }
      
      ind++; 
//.........这里部分代码省略.........
开发者ID:DynamicBrute,项目名称:SARSRover,代码行数:101,代码来源:RoverFi.cpp

示例6: serverLoop

int WiFiManager::serverLoop()
{
    // Check for any mDNS queries and send responses
    mdns.update();
    String s;

    WiFiClient client = server_s.available();
    if (!client) {
        return(WM_WAIT);
    }

    DEBUG_PRINT("New client");
    
    // Wait for data from client to become available
    while(client.connected() && !client.available()){
        delay(1);
    }
    
    // Read the first line of HTTP request
    String req = client.readStringUntil('\r');
    
    // First line of HTTP request looks like "GET /path HTTP/1.1"
    // Retrieve the "/path" part by finding the spaces
    int addr_start = req.indexOf(' ');
    int addr_end = req.indexOf(' ', addr_start + 1);
    if (addr_start == -1 || addr_end == -1) {
        DEBUG_PRINT("Invalid request: ");
        DEBUG_PRINT(req);
        return(WM_WAIT);
    }
    req = req.substring(addr_start + 1, addr_end);
    DEBUG_PRINT("Request: ");
    DEBUG_PRINT(req);
    client.flush();

    if (req == "/")
    {
        s = HTTP_200;
        String head = HTTP_HEAD;
        head.replace("{v}", "Config ESP");
        s += head;
        s += HTTP_SCRIPT;
        s += HTTP_STYLE;
        s += HTTP_HEAD_END;

        int n = WiFi.scanNetworks();
        DEBUG_PRINT("scan done");
        if (n == 0) {
            DEBUG_PRINT("no networks found");
            s += "<div>No networks found. Refresh to scan again.</div>";
        }
        else {
            for (int i = 0; i < n; ++i)
            {
                DEBUG_PRINT(WiFi.SSID(i));
                DEBUG_PRINT(WiFi.RSSI(i));
                String item = HTTP_ITEM;
                item.replace("{v}", WiFi.SSID(i));
                s += item;
                delay(10);
            }
        }
        
        s += HTTP_FORM;
        s += HTTP_END;
        
        DEBUG_PRINT("Sending config page");
    }
    else if ( req.startsWith("/s") ) {
        String qssid;
        qssid = urldecode(req.substring(8,req.indexOf('&')).c_str());
        DEBUG_PRINT(qssid);
        DEBUG_PRINT("");
        req = req.substring( req.indexOf('&') + 1);
        String qpass;
        qpass = urldecode(req.substring(req.lastIndexOf('=')+1).c_str());

        setEEPROMString(0, 32, qssid);
        setEEPROMString(32, 64, qpass);

        EEPROM.commit();

        s = HTTP_200;
        String head = HTTP_HEAD;
        head.replace("{v}", "Saved config");
        s += HTTP_STYLE;
        s += HTTP_HEAD_END;
        s += "saved to eeprom...<br/>resetting in 10 seconds";
        s += HTTP_END;
        client.print(s);
        client.flush();

        DEBUG_PRINT("Saved WiFiConfig...restarting.");
        return WM_DONE;
    }
    else
    {
        s = HTTP_404;
        DEBUG_PRINT("Sending 404");
    }
//.........这里部分代码省略.........
开发者ID:Dietmar-Franken,项目名称:WiFiWaterbedHeater,代码行数:101,代码来源:WiFiManager.cpp

示例7: atoi


//.........这里部分代码省略.........
      DEBUG_OUTPUT.print("headerValue: ");
      DEBUG_OUTPUT.println(headerValue);
      #endif

      if (headerName == "Content-Type"){
        if (headerValue.startsWith("text/plain")){
          isForm = false;
        } else if (headerValue.startsWith("application/x-www-form-urlencoded")){
          isForm = false;
          isEncoded = true;
        } else if (headerValue.startsWith("multipart/")){
          boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);
          isForm = true;
        }
      } else if (headerName == "Content-Length"){
        contentLength = headerValue.toInt();
      } else if (headerName == "Host"){
        _hostHeader = headerValue;
      }
    }

    if (!isForm){
      size_t plainLength;
      char* plainBuf = readBytesWithTimeout(client, contentLength, plainLength, HTTP_MAX_POST_WAIT);
      if (plainLength < contentLength) {
      	free(plainBuf);
      	return false;
      }
      if (contentLength > 0) {
        if (searchStr != "") searchStr += '&';
        if(isEncoded){
          //url encoded form
          String decoded = urlDecode(plainBuf);
          size_t decodedLen = decoded.length();
          memcpy(plainBuf, decoded.c_str(), decodedLen);
          plainBuf[decodedLen] = 0;
          searchStr += plainBuf;
        }
        _parseArguments(searchStr);
        if(!isEncoded){
          //plain post json or other data
          RequestArgument& arg = _currentArgs[_currentArgCount++];
          arg.key = "plain";
          arg.value = String(plainBuf);
        }

  #ifdef DEBUG_ESP_HTTP_SERVER
        DEBUG_OUTPUT.print("Plain: ");
        DEBUG_OUTPUT.println(plainBuf);
  #endif
        free(plainBuf);
      }
    }

    if (isForm){
      _parseArguments(searchStr);
      if (!_parseForm(client, boundaryStr, contentLength)) {
        return false;
      }
    }
  } else {
    String headerName;
    String headerValue;
    //parse headers
    while(1){
      req = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (req == "") break;//no moar headers
      int headerDiv = req.indexOf(':');
      if (headerDiv == -1){
        break;
      }
      headerName = req.substring(0, headerDiv);
      headerValue = req.substring(headerDiv + 2);
      _collectHeader(headerName.c_str(),headerValue.c_str());

	  #ifdef DEBUG_ESP_HTTP_SERVER
	  DEBUG_OUTPUT.print("headerName: ");
	  DEBUG_OUTPUT.println(headerName);
	  DEBUG_OUTPUT.print("headerValue: ");
	  DEBUG_OUTPUT.println(headerValue);
	  #endif

	  if (headerName == "Host"){
        _hostHeader = headerValue;
      }
    }
    _parseArguments(searchStr);
  }
  client.flush();

#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("Request: ");
  DEBUG_OUTPUT.println(url);
  DEBUG_OUTPUT.print(" Arguments: ");
  DEBUG_OUTPUT.println(searchStr);
#endif

  return true;
}
开发者ID:9mrcookie9,项目名称:Arduino,代码行数:101,代码来源:Parsing.cpp

示例8: mainloop

void mainloop()
{
  ///////////////////
  // do data logging
  ///////////////////
  if (millis() >= ulNextMeas_ms)
  {
    ds18b20();
    sendTeperatureTS(temp1, temp2, temp3, temp4);

    ulNextMeas_ms = millis() + ulMeasDelta_ms;

    pfTemp1[ulMeasCount % ulNoMeasValues] = temp1;
    pfTemp2[ulMeasCount % ulNoMeasValues] = temp2;
    pfTemp3[ulMeasCount % ulNoMeasValues] = temp3;
    pfTemp4[ulMeasCount % ulNoMeasValues] = temp4;
    pulTime[ulMeasCount % ulNoMeasValues] = millis() / 1000 + ulSecs2000_timer;

    Serial.print("Logging Temperature1: ");
    Serial.print(pfTemp1[ulMeasCount % ulNoMeasValues]);
    Serial.print(" deg Celsius - Temperature2: ");
    Serial.print(pfTemp2[ulMeasCount % ulNoMeasValues]);
    Serial.print(" deg Celsius - Temperature3: ");
    Serial.print(pfTemp3[ulMeasCount % ulNoMeasValues]);
    Serial.print(" deg Celsius - Temperature4: ");
    Serial.print(pfTemp4[ulMeasCount % ulNoMeasValues]);
    Serial.print(" deg Celsius - Time: ");
    Serial.println(pulTime[ulMeasCount % ulNoMeasValues]);

    ulMeasCount++;
  }

  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  unsigned long ultimeout = millis() + 250;
  while (!client.available() && (millis() < ultimeout) )
  {
    delay(1);
  }
  if (millis() > ultimeout)
  {
    Serial.println("client connection time-out!");
    return;
  }

  // Read the first line of the request
  String sRequest = client.readStringUntil('\r');
  //Serial.println(sRequest);
  client.flush();

  // stop client, if request is empty
  if (sRequest == "")
  {
    Serial.println("empty request! - stopping client");
    client.stop();
    return;
  }

  // get path; end of path is either space or ?
  // Syntax is e.g. GET /?pin=MOTOR1STOP HTTP/1.1
  String sPath = "", sParam = "", sCmd = "";
  String sGetstart = "GET ";
  int iStart, iEndSpace, iEndQuest;
  iStart = sRequest.indexOf(sGetstart);
  if (iStart >= 0)
  {
    iStart += +sGetstart.length();
    iEndSpace = sRequest.indexOf(" ", iStart);
    iEndQuest = sRequest.indexOf("?", iStart);

    // are there parameters?
    if (iEndSpace > 0)
    {
      if (iEndQuest > 0)
      {
        // there are parameters
        sPath  = sRequest.substring(iStart, iEndQuest);
        sParam = sRequest.substring(iEndQuest, iEndSpace);
      }
      else
      {
        // NO parameters
        sPath  = sRequest.substring(iStart, iEndSpace);
      }
    }
  }

  ///////////////////////////////////////////////////////////////////////////////
  // output parameters to serial, you may connect e.g. an Arduino and react on it
  ///////////////////////////////////////////////////////////////////////////////
  if (sParam.length() > 0)
  {
    int iEqu = sParam.indexOf("=");
//.........这里部分代码省略.........
开发者ID:TobiasN82,项目名称:SMASE,代码行数:101,代码来源:main.cpp

示例9: loop

void Humure::loop()
{
  // Check if a client has connected
  WiFiClient client = this->server.available();
  if (!client) {
    return;
  }
  Serial.println("");
  Serial.println("New client");

  // Wait for data from client to become available
  while(client.connected() && !client.available()){
    delay(1);
  }
  
  // Read the first line of HTTP request
  String req = client.readStringUntil('\r');

  // GET or POST?
  bool req_get;
  if ( req.startsWith("GET") ) {
    req_get = true;
  } else if ( req.startsWith("POST") ) {
    req_get = false;
  } else {
    Serial.print("Invalid request: ");
    Serial.println(req);
    return;
  }
  
  // First line of HTTP request looks like "GET /path HTTP/1.1"
  // Retrieve the "/path" part by finding the spaces
  int addr_start = req.indexOf(' ');
  int addr_end = req.indexOf(' ', addr_start + 1);
  if (addr_start == -1 || addr_end == -1) {
    Serial.print("Invalid request: ");
    Serial.println(req);
    return;
  }
  req = req.substring(addr_start + 1, addr_end);

  Serial.print("Request ");
  if (req_get)
  {
    Serial.print("GET");
  } else {
    Serial.print("POST");
  }
  Serial.print(" : ");
  Serial.println(req);
  client.flush();

  if ( req_get ) {
    if ( req == "/" ) {
        readSensor();
        sendFullPage(client);
    } else 
    if ( req ==  "/lamp") {
      jsonValue(client, String( ! led_status) );
    } else 
    if ( req ==  "/temperatur") {
      readSensor();
      jsonValue(client, String( this->t) );
    } else 
    if ( req ==  "/humidity") {
      readSensor();
      jsonValue(client, String( this->h) );
    } else {
      client.print("HTTP/1.1 404 Not Found\r\n\r\n");
    }
  } else {
    if ( req == "/lamp/on" ) {
        led_status = 0;
        jsonValue(client, String( ! led_status) );
    } else
    if ( req =="/lamp/off" ) {
        led_status = 1;
        jsonValue(client, String( ! led_status) );
    } else {
        client.print("HTTP/1.1 404 Not Found\r\n\r\n");
    }
     digitalWrite(this->led, led_status);
  }

  Serial.println("Done with client");
}
开发者ID:railsgirlssb,项目名称:humure_esp8266,代码行数:86,代码来源:Humure.cpp

示例10: ProcessHTTP

// Process HTTP requests -- just call it inside the loop() function
void WebConfig::ProcessHTTP()
{
	// Accept any new web connection
	WiFiClient httpClient = pHttpServer->available();
	if (!httpClient) return;

	// Read the entire request
	String req = httpClient.readString();
	httpClient.flush();

	// after some time, do not open the web interface anymore.
	//if (millis() - startMillis > 2*60000) return;

	// response header
	String s;

	if (strlen(webLogin) > 0 || strlen(webPassword) > 0)
	{
		int authPos = req.indexOf("Authorization: Basic");

		if (authPos == -1)
		{
			// request authentication
			s = "HTTP/1.0 401 Authorization Required\r\nWWW-Authenticate: Basic realm=\"" + String(apName) + "\"\r\n\r\n";
			s += "<h1><b>ACCESS DENIED</b></h1>";
			httpClient.write(s.c_str(), s.length());
			httpClient.flush();
			return;
		}

		// there is authentication info, check it
		String authInfo = req.substring(authPos + 21);
		int endLinePos = authInfo.indexOf("\r");
		if (endLinePos == -1) { httpClient.print("Malformed request."); httpClient.stop(); return; }
		authInfo = authInfo.substring(0, endLinePos);
		if (strncmp(base64Auth, authInfo.c_str(), 64))
		{
			s = "<h1><b>ACCESS DENIED</b></h1>";
			httpClient.write(s.c_str(), s.length());
			httpClient.flush();
			return;
		}
	}

	byte mac[6];
	WiFi.macAddress(mac);
	String m = String(mac[0],HEX) + ":" + String(mac[1],HEX) + ":" + String(mac[2],HEX) + ":" + String(mac[3],HEX) + ":" + String(mac[4],HEX) + ":" + String(mac[5],HEX);

	//
	// generate HTTP response
	//

	// authentication succeeded, proceed normally
	s = "HTTP/1.1 200 OK\r\n";
	s += "Content-Type: text/html\r\n\r\n";
	s += "<!DOCTYPE HTML>\r\n<html><body>\r\n";

	// If there are parms, update variables and save settings
	bool updated = ProcessParms(req);
	if (updated)
	{
		s += "Parameters have been updated and microcontroller will restart.<br><br>\r\n";
	}

	// javascript to save configuration
	s += "<script>\r\n";
	s += "function save()\r\n";
	s += "{\r\n";
	s += "var webPort = document.getElementById('web_port').value;\r\n";
	s += "var webLogin = document.getElementById('web_login').value;\r\n";
	s += "var webPassword = document.getElementById('web_pass').value;\r\n";
	s += "var webPassword2 = document.getElementById('web_pass2').value;\r\n";
	s += "var modeap = document.getElementById('modeap').checked;\r\n";
	s += "if (modeap) isAP = true; else isAP = false;\r\n";
	s += "var apName = document.getElementById('ap_ssid').value;\r\n";
	s += "var apPassword = document.getElementById('ap_pass').value;\r\n";
	s += "var apPassword2 = document.getElementById('ap_pass2').value;\r\n";
	s += "var apChannel = document.getElementById('apChannel').value;\r\n";
	s += "var ssid = document.getElementById('ssid').value;\r\n";
	s += "var password = document.getElementById('pass').value;\r\n";
	s += "var password2 = document.getElementById('pass2').value;\r\n";
	s += "var udpPort = document.getElementById('udpPort').value;\r\n";
	s += "var tcpPort = document.getElementById('tcpPort').value;\r\n";
	s += "if (webPassword != webPassword2) { alert('WEB passwords dont match'); return; }\r\n";
	s += "if (apPassword != apPassword2) { alert('AP passwords dont match'); return; }\r\n";
	s += "if (password != password2) { alert('Router passwords dont match'); return; }\r\n";
	s += "window.location.search=webPort + '&' + webLogin + '&' + webPassword + '&' + btoa(webLogin+':'+webPassword) + '&' + (isAP?'1':'0') + '&' + apName + '&' + apPassword + '&' + apChannel + '&' + ssid + '&' + password + '&' + udpPort + '&' + tcpPort;\r\n";
	s += "}\r\n";
	s += "</script>\r\n";

	// write first part of response
	httpClient.write(s.c_str(), s.length());

	// title and mac address
	s = "<b>" + String(name) + "</b><br>\r\n";
	s += "MAC: " + m + "<br>\r\n";

	// web interface configuration
	s += "<table border=1>\r\n";
//.........这里部分代码省略.........
开发者ID:chancsc,项目名称:ESP_WebConfig,代码行数:101,代码来源:WebConfig.cpp

示例11: if

void ESP8266WebServer::handleClient()
{
  WiFiClient client = _server.available();
  if (!client) {
    return;
  }

#ifdef DEBUG
  Serial.println("New client");
#endif
  // Wait for data from client to become available
  while(client.connected() && !client.available()){
    delay(1);
  }

  // Read the first line of HTTP request
  String req = client.readStringUntil('\r');
  client.readStringUntil('\n');

  HTTPMethod method = HTTP_GET;
  if (req.startsWith("POST")) {
    method = HTTP_POST;
  }

  // First line of HTTP request looks like "GET /path HTTP/1.1"
  // Retrieve the "/path" part by finding the spaces
  int addr_start = req.indexOf(' ');
  int addr_end = req.indexOf(' ', addr_start + 1);
  if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG
    Serial.print("Invalid request: ");
    Serial.println(req);
#endif
    return;
  }

  req = req.substring(addr_start + 1, addr_end);

  String formData;
  if (method == HTTP_POST) {
    int contentLength = -1;
    int headerCount = 0;
    while(headerCount < 1024) { // there shouldn't be that much really
      String line = client.readStringUntil('\r');
      client.readStringUntil('\n');

      if (line.length() > 0) {  // this is a header
        ++headerCount;
        if (contentLength < 0 && line.startsWith("Content-Length")) {
          // get content length from the header
          int valuePos = line.indexOf(' ', 14);
          if (valuePos > 0) {
            String valueStr = line.substring(valuePos+1);
            contentLength = valueStr.toInt();
#ifdef DEBUG
            Serial.print("Content-Length: ");
            Serial.println(contentLength);
#endif
          }
        }
      }
      else {
        break;
      }
    }
#ifdef DEBUG
    Serial.print("headerCount=");
    Serial.println(headerCount);
#endif
    if (contentLength >= 0) {
      formData = "";
      int n = 0;   // timeout counter
      while (formData.length() < contentLength && ++n < 3)
        formData += client.readString();
    }
    else {
      formData = client.readStringUntil('\r'); // will return after timing out once
    }
  }
  else if (method == HTTP_GET) {
    int args_start = req.indexOf('?');
    if (args_start != -1) {
      formData = req.substring(args_start + 1);
      req = req.substring(0, args_start);
    }
  }

  client.flush();

#ifdef DEBUG
  Serial.print("Request: ");
  Serial.println(req);
  Serial.print("Args: ");
  Serial.println(formData);
#endif

  _parseArguments(formData);
  _handleRequest(client, req, method);

}
开发者ID:ashishverma2614,项目名称:esp8266-Arduino,代码行数:100,代码来源:ESP8266WebServer.cpp

示例12: if


//.........这里部分代码省略.........
  int hasSearch = url.indexOf('?');
  if (hasSearch != -1){
    searchStr = url.substring(hasSearch + 1);
    url = url.substring(0, hasSearch);
  }
  _currentUri = url;
  
  HTTPMethod method = HTTP_GET;
  if (methodStr == "POST") {
    method = HTTP_POST;
  } else if (methodStr == "DELETE") {
    method = HTTP_DELETE;
  } else if (methodStr == "PUT") {
    method = HTTP_PUT;
  } else if (methodStr == "PATCH") {
    method = HTTP_PATCH;
  }
  _currentMethod = method;
  
#ifdef DEBUG
  DEBUG_OUTPUT.print("method: ");
  DEBUG_OUTPUT.print(methodStr);
  DEBUG_OUTPUT.print(" url: ");
  DEBUG_OUTPUT.print(url);
  DEBUG_OUTPUT.print(" search: ");
  DEBUG_OUTPUT.println(searchStr);
#endif

  String formData;
  // below is needed only when POST type request
  if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){
    String boundaryStr;
    String headerName;
    String headerValue;
    bool isForm = false;
    uint32_t contentLength = 0;
    //parse headers
    while(1){
      req = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (req == "") break;//no moar headers
      int headerDiv = req.indexOf(':');
      if (headerDiv == -1){
        break;
      }
      headerName = req.substring(0, headerDiv);
      headerValue = req.substring(headerDiv + 2);
      if (headerName == "Content-Type"){
        if (headerValue.startsWith("text/plain")){
          isForm = false;
        } else if (headerValue.startsWith("multipart/form-data")){
          boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);
          isForm = true;
        }
      } else if (headerName == "Content-Length"){
        contentLength = headerValue.toInt();
      }
    }
  
    if (!isForm){
      if (searchStr != "") searchStr += '&';
      //some clients send headers first and data after (like we do)
      //give them a chance
      int tries = 100;//100ms max wait
      while(!client.available() && tries--)delay(1);
      size_t plainLen = client.available();
      char *plainBuf = (char*)malloc(plainLen+1);
      client.readBytes(plainBuf, plainLen);
      plainBuf[plainLen] = '\0';
#ifdef DEBUG
      DEBUG_OUTPUT.print("Plain: ");
      DEBUG_OUTPUT.println(plainBuf);
#endif
      if(plainBuf[0] == '{' || plainBuf[0] == '[' || strstr(plainBuf, "=") == NULL){
        //plain post json or other data
        searchStr += "plain=";
        searchStr += plainBuf;
      } else {
        searchStr += plainBuf;
      }
      free(plainBuf);
    }
    _parseArguments(searchStr);
    if (isForm){
      _parseForm(client, boundaryStr, contentLength);
    }
  } else {
    _parseArguments(searchStr);
  }
  client.flush();

#ifdef DEBUG
  DEBUG_OUTPUT.print("Request: ");
  DEBUG_OUTPUT.println(url);
  DEBUG_OUTPUT.print(" Arguments: ");
  DEBUG_OUTPUT.println(searchStr);
#endif

  return true;
}
开发者ID:Red680812,项目名称:WeMos_Boards,代码行数:101,代码来源:Parsing.cpp

示例13: updateCurTime

////////////////////////////////////
// Scrape UTC Time from server
////////////////////////////////////
char* updateCurTime(void) {
    static int timeout_busy=0;
    int ipos;
    timeout_busy=0; //reset

    const char* timeServer = "aws.amazon.com";

    // send a bad header on purpose, so we get a 400 with a DATE: timestamp
    const char* timeServerGet = "GET example.com/ HTTP/1.1";
    String utctime;
    String GmtDate;
    static char dateStamp[20];
    static char chBuf[200];
    char utctimeraw[80];
    char* dpos;

    WiFiClient client;
    if (client.connect(timeServer, 80)) {
        //Send Request
        client.println(timeServerGet);
        client.println();
        while((!client.available())&&(timeout_busy++<5000)){
          // Wait until the client sends some data
          delay(1);
        }

        // kill client if timeout
        if(timeout_busy>=5000) {
            client.flush();
            client.stop();
            Serial.println("timeout receiving timeserver data\n");
            return dateStamp;
        }

        // read the http GET Response
        String req2 = client.readString();
        // Serial.println("");
        // Serial.println("");
        // Serial.print(req2);
        // Serial.println("");
        // Serial.println("");

        // close connection
        delay(1);
        client.flush();
        client.stop();

        ipos = req2.indexOf("Date:");
        if(ipos>0) {
          GmtDate = req2.substring(ipos,ipos+35);
          // Serial.println(GmtDate);
          utctime = GmtDate.substring(18,22) + getMonth(GmtDate.substring(14,17)) + GmtDate.substring(11,13) + GmtDate.substring(23,25) + GmtDate.substring(26,28) + GmtDate.substring(29,31);
          // Serial.println(utctime.substring(0,14));
          utctime.substring(0,14).toCharArray(dateStamp, 20);
        }
    }
    else {
      Serial.println("did not connect to timeserver\n");
    }
    timeout_busy=0;     // reset timeout
    return dateStamp;   // Return latest or last good dateStamp
}
开发者ID:jamesbowles,项目名称:aws-sdk-arduino,代码行数:65,代码来源:ESP8266AWSImplentations.cpp

示例14: atoi


//.........这里部分代码省略.........
      DEBUG_OUTPUT.print("headerName: ");
      DEBUG_OUTPUT.println(headerName);
      DEBUG_OUTPUT.print("headerValue: ");
      DEBUG_OUTPUT.println(headerValue);
      #endif

      if (headerName.equalsIgnoreCase(FPSTR(Content_Type))){
        using namespace mime;
        if (headerValue.startsWith(FPSTR(mimeTable[txt].mimeType))){
          isForm = false;
        } else if (headerValue.startsWith(F("application/x-www-form-urlencoded"))){
          isForm = false;
          //isEncoded = true;
        } else if (headerValue.startsWith(F("multipart/"))){
          boundaryStr = headerValue.substring(headerValue.indexOf('=') + 1);
          boundaryStr.replace("\"","");
          isForm = true;
        }
      } else if (headerName.equalsIgnoreCase(F("Content-Length"))){
        contentLength = headerValue.toInt();
      } else if (headerName.equalsIgnoreCase(F("Host"))){
        _hostHeader = headerValue;
      }
    }

    // always parse url for key/value pairs
    _parseArguments(searchStr);

    if (!isForm) {
      if (contentLength) {

        // add key=value: plain={body} (post json or other data)

        size_t plainLength;
        char* plainBuf = readBytesWithTimeout(client, contentLength, plainLength, HTTP_MAX_POST_WAIT);
        if (plainLength < contentLength) {
          free(plainBuf);
          return false;
        }

        RequestArgument& arg = _currentArgs[_currentArgCount++];
        arg.key = F("plain");
        arg.value = String(plainBuf);

        free(plainBuf);

      }
    } else { // isForm is true

      if (!_parseForm(client, boundaryStr, contentLength)) {
        return false;
      }

    }
  } else {
    String headerName;
    String headerValue;
    //parse headers
    while(1){
      req = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (req == "") break;//no moar headers
      int headerDiv = req.indexOf(':');
      if (headerDiv == -1){
        break;
      }
      headerName = req.substring(0, headerDiv);
      headerValue = req.substring(headerDiv + 2);
      _collectHeader(headerName.c_str(),headerValue.c_str());

#ifdef DEBUG_ESP_HTTP_SERVER
      DEBUG_OUTPUT.print(F("headerName: "));
      DEBUG_OUTPUT.println(headerName);
      DEBUG_OUTPUT.print(F("headerValue: "));
      DEBUG_OUTPUT.println(headerValue);
#endif

      if (headerName.equalsIgnoreCase("Host")){
        _hostHeader = headerValue;
      }
    }
    _parseArguments(searchStr);
  }
  client.flush();

#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print(F("Request: "));
  DEBUG_OUTPUT.println(url);
  DEBUG_OUTPUT.print(F("Arguments: "));
  DEBUG_OUTPUT.println(searchStr);

  DEBUG_OUTPUT.println(F("final list of key/value pairs:"));
  for (int i = 0; i < _currentArgCount; i++)
    DEBUG_OUTPUT.printf("  key:'%s' value:'%s'\r\n",
      _currentArgs[i].key.c_str(),
      _currentArgs[i].value.c_str());
#endif

  return true;
}
开发者ID:dagger82,项目名称:Arduino,代码行数:101,代码来源:Parsing.cpp


注:本文中的WiFiClient::flush方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。