Skip to content

Instantly share code, notes, and snippets.

@JiriBilek
Last active July 4, 2021 05:56
Show Gist options
  • Save JiriBilek/9d2b6c1578ba7cf7a869e5577564dfe3 to your computer and use it in GitHub Desktop.
Save JiriBilek/9d2b6c1578ba7cf7a869e5577564dfe3 to your computer and use it in GitHub Desktop.
/*
Sketch for ESP8266 testing the issue 13, namely multiple tcp server connections
https://github.com/JiriBilek/WiFiSpi/issues/13
*/
#include <ESP8266WiFi.h>
const char* ssid = "****";
const char* password = "****";
#define maxClients 8
WiFiClient clients[maxClients];
WiFiServer TCPserver(80);
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.print("Connecting ");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
TCPserver.begin();
if (TCPserver.status() != CLOSED)
{
Serial.println("Server started");
}
}
void loop() {
static long nextUpdate = 0;
long startTime = millis();
WiFiClient client = TCPserver.available();
long calcTime = millis() - startTime;
if ( calcTime > 100 )
{
Serial.print("Used time: ");
Serial.println(calcTime);
}
if (client.connected()) {
Serial.println("Client is connected");
bool clientIsNew = true;
//Serial.printf("+ %d.%d.%d.%d:%d\n", client.remoteIP()[0], client.remoteIP()[1], client.remoteIP()[2], client.remoteIP()[3], client.remotePort());
for (byte i = 0 ; i < maxClients; i++)
{
//Serial.printf("* %d.%d.%d.%d:%d\n", clients[i].remoteIP()[0], clients[i].remoteIP()[1], clients[i].remoteIP()[2], clients[i].remoteIP()[3], clients[i].remotePort());
if (client.remoteIP() == clients[i].remoteIP() && client.remotePort() == clients[i].remotePort())
{
clientIsNew = false;
}
}
if ( clientIsNew )
{
Serial.println("Client is new");
for (byte i = 0 ; i < maxClients; i++)
{
if (clients[i].connected() == false )
{
Serial.print("New client! : ");
Serial.println(i);
client.write("HTTP/1.1 200 OK\r\n\r\n");
client.write("<<hello;->>\r\n");
clients[i] = client;
break;
}
}
}
}
if ( nextUpdate == 0 || millis() > nextUpdate )
{
for (byte i = 0; i < maxClients; i++)
{
if (clients[i].connected())
{
char Data[200];
snprintf(Data, sizeof Data, "<<data;%d:%lu>>\n", i, millis());
clients[i].write(Data);
}
}
nextUpdate = millis() + 500;
}
}
@JiriBilek
Copy link
Author

JiriBilek commented Jan 6, 2019

Revision 1 does not allow more than 1 connection due to buggy comparison:

    bool clientIsNew = true;

    for (byte i = 0 ; i < 4; i++)
    {
      if (client == clients[i])
      {
        clientIsNew = false;
      }
}

Revision 2 works fine for 8 clients

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment