Esp8266 connection problems

Hi, I am use a esp8266 and I am trying to get a simple TCP raw socket server started, the connection is established but immediately closes!

Someone could tell me what is my mistake?

#include <ESP8266WiFi.h>
#include <WiFiClient.h>

const char* ssid = "<>";
const char* password = "<>";

// Start a TCP Server on port 5045
WiFiServer server(5045);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid,password);
  Serial.println("");
  //Wait for connection
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.print("Connected to "); Serial.println(ssid);
  Serial.print("IP Address: "); Serial.println(WiFi.localIP());
 
  // Start the TCP server
  server.begin();
}

void loop() {
  WiFiClient client = server.available();
  if (client) {
    if (client.connected()) {
      Serial.println("Connected to client");   
    }
    if (client.available() > 0) {
      // Read incoming message
      char inChar = client.read();
      // Send back something to the clinet
      server.write(inChar);
      // Echo input on Serial monitor
      Serial.write(inChar);
    }
  }
}

You create a client inside loop(). When loop() exits, client goes out of scope so it stopped. You probably want client to be global and then depending on whether or not it is connected, check for data or get a new client

Since loop neer exits not sure how the clinet can go out of scope.

However since the loop never exits everytime it comes round the old client will be left hanging anf a new client created.

So I disagree on the cause, but agree on the solution, make client global and initialise it in setup.

countrypaul:
Since loop neer exits not sure how the clinet can go out of scope.

However since the loop never exits everytime it comes round the old client will be left hanging anf a new client created.

So I disagree on the cause, but agree on the solution, make client global and initialise it in setup.

Your understanding of setup() and loop() are not accurate. The arduino main() program basically does

int main() {
  setup();
  while(1) {
    loop();
    SerialEvent();
  }
}

So loop() most definitely terminates and main calls it again. This most definitely triggers all local variables to go out of scope and depending on the object, the destructor will be called. [I didn't look at that particular class so can't comment on 'client']

Blh64 - Sorry, I have no idea why I wrote that, clearly completely wrong, even if loop never exited it would be completely wrong since that scope would end at the } regardless.