Add WiFiServer hasClient and WiFiTelnetToSerial example (#394)

WiFiTelnetToSerial is also a test for hasClient().
This commit is contained in:
bbx10
2017-05-22 20:12:39 -10:00
committed by Me No Dev
parent db09ca8c16
commit 432bcf5a0a
3 changed files with 157 additions and 2 deletions

View File

@ -40,9 +40,16 @@ void WiFiServer::stopAll(){}
WiFiClient WiFiServer::available(){
if(!_listening)
return WiFiClient();
int client_sock;
if (_accepted_sockfd >= 0) {
client_sock = _accepted_sockfd;
_accepted_sockfd = -1;
}
else {
struct sockaddr_in _client;
int cs = sizeof(struct sockaddr_in);
int client_sock = accept(sockfd, (struct sockaddr *)&_client, (socklen_t*)&cs);
client_sock = accept(sockfd, (struct sockaddr *)&_client, (socklen_t*)&cs);
}
if(client_sock >= 0){
int val = 1;
if(setsockopt(client_sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, sizeof(int)) == ESP_OK) {
@ -70,6 +77,8 @@ void WiFiServer::begin(){
return;
fcntl(sockfd, F_SETFL, O_NONBLOCK);
_listening = true;
_noDelay = false;
_accepted_sockfd = -1;
}
void WiFiServer::setNoDelay(bool nodelay) {
@ -80,6 +89,19 @@ bool WiFiServer::getNoDelay() {
return _noDelay;
}
bool WiFiServer::hasClient() {
if (_accepted_sockfd >= 0) {
return true;
}
struct sockaddr_in _client;
int cs = sizeof(struct sockaddr_in);
_accepted_sockfd = accept(sockfd, (struct sockaddr *)&_client, (socklen_t*)&cs);
if (_accepted_sockfd >= 0) {
return true;
}
return false;
}
void WiFiServer::end(){
close(sockfd);
sockfd = -1;

View File

@ -26,6 +26,7 @@
class WiFiServer : public Server {
private:
int sockfd;
int _accepted_sockfd = -1;
uint16_t _port;
uint8_t _max_clients;
bool _listening;
@ -34,13 +35,14 @@ class WiFiServer : public Server {
public:
void listenOnLocalhost(){}
WiFiServer(uint16_t port=80, uint8_t max_clients=4):sockfd(-1),_port(port),_max_clients(max_clients),_listening(false){}
WiFiServer(uint16_t port=80, uint8_t max_clients=4):sockfd(-1),_accepted_sockfd(-1),_port(port),_max_clients(max_clients),_listening(false),_noDelay(false){}
~WiFiServer(){ end();}
WiFiClient available();
WiFiClient accept(){return available();}
void begin();
void setNoDelay(bool nodelay);
bool getNoDelay();
bool hasClient();
size_t write(const uint8_t *data, size_t len);
size_t write(uint8_t data){
return write(&data, 1);