me-no-dev / AsyncTCP

Async TCP Library for ESP32
GNU Lesser General Public License v3.0
757 stars 439 forks source link

examples #107

Closed vult-r closed 4 years ago

vult-r commented 4 years ago

Thanks for the great work, got aSync running on between esp32s, c++ and android studio. All working nicely so thanks a lot. I noticed there are no esp32 examples. So for what it's worth here is my test code for client+server for sending Strings , you can easilly re-write to c-string or uint8_t arrays for binary throughput etc etc.

server code

#include <WiFi.h>
#include <AsyncTCP.h>
#include <vector>

const char* ssid     = "yourNetwork";
const char* password = "yourPassword";

short MaxConnections = 2;

AsyncServer tcpServer(7809);
static std::vector<AsyncClient*> clients; 
static std::vector<AsyncClient*>::iterator cl;
unsigned long lastTick;

void addClient(AsyncClient* client)
{
      clients.push_back(client);
}

void removeClient(AsyncClient* client)
{
    for(cl = clients.begin(); cl!= clients.end(); cl++)    
    {
        if( *cl == client )
        {   
            clients.erase(cl);
            return;
        }
    }
}

void removeAllClients()
{
    for(cl = clients.begin(); cl!= clients.end(); cl++)    
    {
        (*cl)->close();
    }
}

void sendStringToClient( AsyncClient* client, String sendMsg )
{
    if( !client->canSend() ) { return; }

    if ( client->space() > sendMsg.length() ) 
    {
          client->add( sendMsg.c_str() , sendMsg.length() );
          client->send();
    }
}

void sendStringToClientIP( String ip , String sendMsg )
{
    for(cl = clients.begin(); cl!= clients.end(); cl++)    
    {
        if( (*cl)->remoteIP().toString() == ip )
        {   
            sendStringToClient( (*cl) , sendMsg );
            return;
        }
    }
}

void sendStringToAllClients( String sendMsg )
{
    for(cl = clients.begin(); cl!= clients.end(); cl++)    
    {
        sendStringToClient( (*cl) , sendMsg );
    }
}

static void handleData(void* arg, AsyncClient* client, void *data, size_t len)
{
    Serial.print("[CALLBACK] data received, ip: " + client->remoteIP().toString());
    Serial.println( " [" + String((char*)data) + "]" );

    // here you could also send a String back by doing this:
    // sendStringToClient( client , "Hello from server!" ); // reply to client
}

static void handleError(void* arg, AsyncClient* client, int8_t error) 
{
    Serial.println("[CALLBACK] client error, ip: " + client->remoteIP().toString());
}

static void handleTimeOut(void* arg, AsyncClient* client, uint32_t time) 
{
    Serial.println("[CALLBACK] ACK timeout, ip: " + client->remoteIP().toString());
}

static void handleDisconnect(void* arg, AsyncClient* client) 
{
    Serial.println("[CALLBACK] client discconnected, ip: " + client->remoteIP().toString());

    removeClient(client);
}

static void setupNewClient(void* arg, AsyncClient* client) 
{
    if( clients.size() >= MaxConnections ) 
    { 
        client->close();
        return; 
    } 

    Serial.println("[SERVER] new client conneced, ip: " + client->remoteIP().toString());

    addClient( client );

    client->setRxTimeout(60);
    client->onData(&handleData, NULL);
    client->onError(&handleError, NULL);
    client->onTimeout(&handleTimeOut, NULL);
    client->onDisconnect(&handleDisconnect, NULL);
}

void setup()
{
    Serial.begin(115200);
    Serial.println("");

    WiFi.begin(ssid, password);
    Serial.print("[WIFI] connecting to network " + String(ssid) );

    while (WiFi.status() != WL_CONNECTED) {  delay(500); Serial.print(".");  }
    Serial.println("[WIFI] connected with Ip: " + WiFi.localIP().toString() );

    tcpServer.onClient( &setupNewClient, &tcpServer );
    tcpServer.begin();
}

void loop()
{
    if( millis() - lastTick > 2000 ) // every 2 sec , (output to Serial + sending to all clients)
    {
        Serial.println("[MAIN] loop still going , connected clients: " + String( clients.size() ) );
        lastTick = millis();

        sendStringToAllClients("hi clients, this is server.");
    }
}

client code

#include <WiFi.h>
#include <AsyncTCP.h>

const char* ssid     = "yourNetwork";
const char* password = "yourPassword";

IPAddress serverIP = IPAddress(192, 168, 1, 41);   // change to server IP

AsyncClient tcpClient;
unsigned long lastTick;

void sendStringToServer( String sendMsg )
{
    if( !tcpClient.connected()) { return; }
    if( !tcpClient.canSend() )  { return; }

    if ( tcpClient.space() > sendMsg.length() ) 
    {
          tcpClient.add( sendMsg.c_str() , sendMsg.length() );
          tcpClient.send();
    }
}

static void handleData(void* arg, AsyncClient* client, void *data, size_t len)
{
    Serial.print("[CALLBACK] data received, ip: " + client->remoteIP().toString());
    Serial.println( " [" + String((char*)data) + "]");

    // or loop through data , using data[i] and len:
    // for ( int i = 0 ; i < len ; i++ ) {
    //     if ( uint8_t*)data[i] == 0 ) { } }

    // could send to server here, by doing:
    // sendToServer( "Hello!"); 
}

static void handleError(void* arg, AsyncClient* client, int8_t error) 
{
    Serial.println("[CALLBACK] error");
}

static void handleTimeOut(void* arg, AsyncClient* client, uint32_t time) 
{
    Serial.println("[CALLBACK] ACK timeout");
}

static void handleDisconnect(void* arg, AsyncClient* client) 
{
    Serial.println("[CALLBACK] discconnected");
}

void setup()
{
    Serial.begin(115200);
    Serial.println("");

    WiFi.begin(ssid, password);
    Serial.print("[WIFI] connecting to network " + String(ssid) );

    while (WiFi.status() != WL_CONNECTED) {  delay(500); Serial.print(".");  }
    Serial.println("[WIFI] connected with Ip: " + WiFi.localIP().toString() );

    tcpClient.onData(&handleData, NULL);
    tcpClient.onError(&handleError, NULL);
    tcpClient.onTimeout(&handleTimeOut, NULL);
    tcpClient.onDisconnect(&handleDisconnect, NULL);

    tcpClient.connect( serverIP , 7809 );
}

void loop()
{
    if( millis() - lastTick > 2000 ) // every 2 sec
    {
        Serial.println("[MAIN] loop still going , connected: " + String( tcpClient.connected() ) );
        lastTick = millis();

        sendStringToServer("hi server! i am client.");
    }
}
stale[bot] commented 4 years ago

[STALE_SET] This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Thank you for your contributions.

stale[bot] commented 4 years ago

[STALE_DEL] This stale issue has been automatically closed. Thank you for your contributions.

CelliesProjects commented 3 years ago

Thanks!

jerryliugithub commented 2 years ago

How to get the disconnected IP correctly? AsyncTcpServer

setownley commented 2 years ago

How to get the disconnected IP correctly? AsyncTcpServer

I'm getting the same.

Is anyone else getting client disconnect ip: 0.0.0.0