mirror of
https://github.com/thooge/esp32-nmea2000-obp60.git
synced 2025-12-13 05:53:06 +01:00
TCP server separated
This commit is contained in:
58
lib/socketserver/GwSocketServer.cpp
Normal file
58
lib/socketserver/GwSocketServer.cpp
Normal file
@@ -0,0 +1,58 @@
|
||||
#include "GwSocketServer.h"
|
||||
|
||||
GwSocketServer::GwSocketServer(const GwConfigHandler *config,GwLog *logger){
|
||||
this->config=config;
|
||||
this->logger=logger;
|
||||
}
|
||||
void GwSocketServer::begin(){
|
||||
server=new WiFiServer(config->getInt(config->serverPort),config->getInt(config->maxClients));
|
||||
server->begin();
|
||||
logger->logString("Socket server created, port=%d",
|
||||
config->getInt(config->serverPort));
|
||||
|
||||
}
|
||||
void GwSocketServer::loop()
|
||||
{
|
||||
WiFiClient client = server->available(); // listen for incoming clients
|
||||
|
||||
if (client){
|
||||
logger->logString("new client connected from %s",
|
||||
client.remoteIP().toString().c_str());
|
||||
clients.push_back(wiFiClientPtr(new WiFiClient(client)));
|
||||
}
|
||||
for (auto it = clients.begin(); it != clients.end();it++)
|
||||
{
|
||||
if ((*it) != NULL)
|
||||
{
|
||||
if (!(*it)->connected())
|
||||
{
|
||||
logger->logString("client disconnect ");
|
||||
(*it)->stop();
|
||||
clients.erase(it);
|
||||
}
|
||||
else
|
||||
{
|
||||
while ((*it)->available())
|
||||
{
|
||||
char c = (*it)->read();
|
||||
//TODO: read data
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
it = clients.erase(it); // Should have been erased by StopClient
|
||||
}
|
||||
}
|
||||
}
|
||||
void GwSocketServer::sendToClients(const char *buf){
|
||||
for (auto it = clients.begin() ; it != clients.end(); it++) {
|
||||
if ( (*it) != NULL && (*it)->connected() ) {
|
||||
(*it)->println(buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int GwSocketServer::numClients(){
|
||||
return clients.size();
|
||||
}
|
||||
23
lib/socketserver/GwSocketServer.h
Normal file
23
lib/socketserver/GwSocketServer.h
Normal file
@@ -0,0 +1,23 @@
|
||||
#ifndef _GWSOCKETSERVER_H
|
||||
#define _GWSOCKETSERVER_H
|
||||
#include "GWConfig.h"
|
||||
#include "GwLog.h"
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <WiFi.h>
|
||||
|
||||
using wiFiClientPtr = std::shared_ptr<WiFiClient>;
|
||||
class GwSocketServer{
|
||||
private:
|
||||
const GwConfigHandler *config;
|
||||
GwLog *logger;
|
||||
std::list<wiFiClientPtr> clients;
|
||||
WiFiServer *server=NULL;
|
||||
public:
|
||||
GwSocketServer(const GwConfigHandler *config,GwLog *logger);
|
||||
void begin();
|
||||
void loop();
|
||||
void sendToClients(const char *buf);
|
||||
int numClients();
|
||||
};
|
||||
#endif
|
||||
Reference in New Issue
Block a user