arduino-libraries / ArduinoHttpClient

Arduino HTTP Client library
288 stars 172 forks source link

http request and socket together #66

Closed ddaydd closed 5 years ago

ddaydd commented 5 years ago

Hi,

Can i have two simultaneous connection and how? When i do a http request, the server close the socket connection. With httpClient.connectionKeepAlive(); i keep the connection but the memory between http and socket seems shared.

could you help me?

here is my reduced code...

#include <SPI.h>
#include <Ethernet.h>
#include <ArduinoHttpClient.h>
char HMD_url[] = "www.homedoudou.fr";
const int PORT = 80;
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 1, 177);
String received;

EthernetClient ethernet;
HttpClient httpClient = HttpClient(ethernet, HMD_url, PORT);
WebSocketClient socketClient = WebSocketClient(ethernet, HMD_url, PORT);

void setup() {
  Serial.begin(57600);
  while (!Serial) {}
  Ethernet.begin(mac, ip);
  socketLoopConnection();
}

void loop() {
  httpGet("/api/get?cle=test");
  if (socketClient.connected()) {
    checkSocketMessage();
    socketClient.beginMessage(TYPE_TEXT);
    socketClient.print("{\"msg\":\"connect\",\"version\":\"1\",\"support\":[\"1\"]}");
    socketClient.endMessage();
    while (socketClient.connected()) {
      checkSocketMessage();
    }
    delay(10000);
  }
  else {
    Serial.println("disconnected");
    socketLoopConnection();
  }
}

void socketLoopConnection() {
  while (!socketClient.connected()) {
    socketClient.begin("/websocket");
    delay(5000);
  }
  Serial.println("connected in socket");
}

void checkSocketMessage() {
  int messageSize = socketClient.parseMessage();
  if (messageSize > 0) {
    received = socketClient.readString();
    Serial.println(received);
  }
}

void httpGet(String url) {
  Serial.print("Send HTTP "); Serial.println(url);
  httpClient.connectionKeepAlive();
  httpClient.get(url);
  int statusCode = httpClient.responseStatusCode();
  Serial.print("Status code: "); Serial.println(statusCode);
  if (statusCode == 200) {
    String response = httpClient.responseBody();
    Serial.print("Response: "); Serial.println(response);
  }
}
sandeepmistry commented 5 years ago

Hi @ddaydd,

You'll need to pass in a different Client for each HttpClient you create in the sketch, please try this:

EthernetClient ethernet1;
EthernetClient ethernet2;
HttpClient httpClient = HttpClient(ethernet1, HMD_url, PORT);
WebSocketClient socketClient = WebSocketClient(ethernet2, HMD_url, PORT);
ddaydd commented 5 years ago

It's too simple and i had missed that. it works. Thank you very much!