-->
Page 1 of 3

Simple TCP server

PostPosted: Mon Dec 07, 2015 11:12 am
by spy king
I am trying to get a simple TCP raw socket server started, but am running into a little trouble.
Would really appreciate some pointers!
I currently am trying this.
Code: Select all
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

// Hardcode WiFi parameters as this isn't going to be moving around.
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() {
  TCPServer();
}

void TCPServer () {
    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);
    }
   


However, when I try to connect using PuTTY, I get a "Connected to client" on the serial monitor, and then a -1, followed by a "Connection was closed by the remote host" on PuTTY.
Any ideas what I am missing? Am I progressing in the right direction?

Re: Simple TCP server

PostPosted: Mon Dec 07, 2015 12:29 pm
by martinayotte
The "WiFiClient client" declaration should be global or static, otherwise it will be destroyed when loop is ending.

Re: Simple TCP server

PostPosted: Mon Dec 07, 2015 2:19 pm
by spy king
Thanks for the input. I now have it working fine!
Code: Select allvoid loop() {
  // listen for incoming clients
 client = server.available();
  if (client){
    Serial.println("Client connected");
    while (client.connected()){
        // Read the incoming TCP command
        String command = ReadTCPCommand(&client);
        // Debugging display command
        command.trim();
        Serial.println(command);
        // Phrase the command
        PhraseTCPCommand(&client, &command);
    }
  }
 }

Re: Simple TCP server

PostPosted: Fri Jan 29, 2016 11:01 am
by ingeea
Hello,

i have the same Problem and i am not finding a solution to do. if i define the WiFiClient tcpclient in Setup it would not compile ( tcpclient is not declared in the Loop()) and if i define it as global the same Problem persists "Connection closed by remote host"

any idea please?