Hello,
I send data to the server with HTTP GET requests.
I want to send data periodically without closing the connection.
The procedure seems to be as follows:
- Create a socket;
- Open the connection;
- Send data every 2 seconds.
However, when I send data one time, the socket state becomes SOCK_CLOSE_WAIT, and I can only send one more time.
After that, the socket state becomes SOCK_CLOSED, and I need to open the connection one more time.
What do I need to add to my code to keep the connection alive? I tried to perform the command setSn_CR(sn, Sn_CR_SEND_KEEP)
, but it didn’t help.
In my program, I first run httpInit()
and then periodically run httpClientRun
.
Here is my code below:
void httpInit(void){
int8_t code;
code = socket(httpClientSocket, Sn_MR_TCP, port, 0);
code = connect(httpClientSocket, addr, 80);
setSn_IR(httpClientSocket, Sn_IR_CON);
}
uint8_t httpSendData(char sensorID[], uint16_t co2Val, uint16_t pm25Val, float tempVal, float humidityVal){
int32_t nbytesRSV;
uint16_t len;
socketState = getSn_SR(httpClientSocket);
if((socketState == SOCK_ESTABLISHED)||(socketState == SOCK_CLOSE_WAIT)){
len = sprintf(request, "GET /api/sensor/update?id=%s&co2=%u&pm25=%u&temp=%.2f&humidity=%.2f HTTP/1.0\r\nHost: myserver.com\r\n\r\n",
sensorID, co2Val, pm25Val, tempVal, humidityVal);
while(len > 0){
int32_t nbytes = send(httpClientSocket, (uint8_t*)&request, len);
if(nbytes<0) return 1;
len -= nbytes;
}
}
else return 1;
return 0;
}
uint8_t reconnectCounter;
void httpClientRun(char sensorID[], uint16_t co2Val, uint16_t pm25Val, float tempVal, float humidityVal)
{
if(httpSendData(sensorID, co2Val, pm25Val, tempVal, humidityVal)){
reconnectCounter++;
if(4 <= reconnectCounter){
sockClose++;
httpInit();
reconnectCounter = 0;
}
}
}