Python Forum

Full Version: python socket connect only sometimes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hallo,
I have program in python to simply connect to TCP server and disconnect:
import socket

HOST = '192.168.1.6'  # The server's hostname or IP address
PORT = 5684 
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.close()
Then I have program for ESP8266:
#include "ESP8266WiFi.h"
 
const char* ssid = "home_wifi";
const char* password =  "12345678";
 
WiFiServer wifiServer(5684);

byte message_buffer[10];
int data_index;
int client_count;

void setup() {
 
  Serial.begin(115200);
 
  delay(1000);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting..");
  }
 
  Serial.print("Connected to WiFi. IP:");
  Serial.println(WiFi.localIP());
 
  wifiServer.begin();
  client_count = 0;
}

void loop() 
{
  WiFiClient client = wifiServer.available();
  //Serial.println("čekám");
  while(!(client = wifiServer.available())){}
    if(client.connected())
    {
      Serial.println("Client Connected");
    }
    
    while(client.connected()){      
      while(client.available()>0){
        // read data from the connected client
        Serial.write(client.read()); 
      }
      //Send Data to connected client
      while(Serial.available()>0)
      {
        client.write(Serial.read());
      }
    }
    client.stop();
    Serial.println("\nClient disconnected");  
}
Program in ESP8266 correctli prints (to serial output) "Client Connected" when I connect to it via Putty (and then "Client disconnected" when I disconnect), but not when I run my python program. It appears only sometimes - I must run my python program few times to get right result. So in most cases, the ESP8266 probably not register socket comming from my PC (which run my python program)

Do anybody know why?
Please help, thanks!