Hi,
I wrote a little program which uses the TCPServer. This works to some extent but has some problems:
- The connection works for the first time, but when closing down the connection and reopening another connection, it is often very slow, or the connection does not work at all.
- After a while it often won’t accept new connections anymore.
- While the connection is open, it works for some while, but after a while of inactivity the connection is shut down by the spark core.
I reduced the program to one which only uses only the basic socket APIs. That one has the same problems. So it is not a problem with TCPServer code.
It seems that if waiting a while before reconnecting it works fine. So the issue seems to be accepting too many connections in a too short amount of time.
Here is the program (I put it into application.cpp and upload use dfu-util). This is running all the code in the loop without ever leaving the loop, but also exiting from the loop each time has the same effect.
#include "application.h"
void setup()
{
pinMode(7, OUTPUT);
}
void loop()
{
sockaddr tServerAddr;
tServerAddr.sa_family = AF_INET;
short port = 80;
tServerAddr.sa_data[0] = (port & 0xFF00) >> 8;
tServerAddr.sa_data[1] = (port & 0x00FF);
tServerAddr.sa_data[2] = 0;
tServerAddr.sa_data[3] = 0;
tServerAddr.sa_data[4] = 0;
tServerAddr.sa_data[5] = 0;
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0)
return;
if (bind(sock, (sockaddr*)&tServerAddr, sizeof(tServerAddr)) < 0)
return;
if (listen(sock, 0) < 0)
return;
while (true)
{
sockaddr tClientAddr;
socklen_t tAddrLen = sizeof(tClientAddr);
int client = accept(sock, (sockaddr*)&tClientAddr, &tAddrLen);
if (client < 0)
continue;
while (true)
{
char buffer[1024];
int readBytes = recv(client, buffer, sizeof(buffer), 0);
if (readBytes < 0)
break;
if (buffer[0] == '1')
{
digitalWrite(7, true);
if (send(client, "on\n", sizeof("on\n"), 0) < 0)
break;
}
else if (buffer[0] == '0')
if (buffer[0] == '1')
{
digitalWrite(7, false);
if (send(client, "off\n", sizeof("off\n"), 0) < 0)
break;
}
else if (buffer[0] == 'q')
{
send(client, "quit\n", sizeof("quit\n"), 0);
break;
}
}
closesocket(client);
}
}
I also updated the CC3000 using the new cc3000-patch-programmer, but that did not improve anything. I tried too boards, they both have the same issue.
I am bit puzzled. It seems this is a problem with the CC3000. But that one is used in many applications and I have problems imagining that it is that buggy. Any hints about would I could be doing wrong?