Sockets, new to this, can't make it recieve data. whats wrong?

 

this is the MQL5 code I use:

//+------------------------------------------------------------------+
//|                                                       Socket.mq5 |
//|       Copyright 2024, Javier Santiago Gaston de Iriarte Cabrera. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, Javier Santiago Gaston de Iriarte Cabrera."
#property link      "https://www.mql5.com"
#property version   "1.00"

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   // Llama a la función para comunicarte con el servidor de Python
   string data = "Datos para procesar";
   string result = CommunicateWithPython(data);
   Print("Resultado recibido del servidor de Python: ", result);

   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   // Aquí puedes añadir cualquier código de limpieza si es necesario
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   // Aquí puedes incluir cualquier lógica adicional que necesites
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int InitSocket()
  {
   int socket_handle = SocketCreate();
   if(socket_handle < 0)
     {
      Print("Error al crear el socket");
      return -1;
     }

   Print("Socket creado con éxito.");

   // Conéctate al servidor de Python
   bool isConnected = SocketConnect(socket_handle, "127.0.0.1", 65432, 5000);
   if(!isConnected)
     {
      int error = GetLastError();
      Print("Error al conectar con el servidor de Python. Código de error: ", error);
      SocketClose(socket_handle);
      return -1;
     }

   Print("Conexión con el servidor de Python establecida.");
   return socket_handle;
  }
//+------------------------------------------------------------------+
//| Función para enviar y recibir datos                              |
//+------------------------------------------------------------------+
string CommunicateWithPython(string data)
  {
   int socket_handle = InitSocket();
   if(socket_handle < 0)
      return "";

   uchar send_buffer[];
   StringToCharArray(data, send_buffer);
   int bytesSent = SocketSend(socket_handle, send_buffer, ArraySize(send_buffer));
   if(bytesSent < 0)
     {
      Print("Error al enviar datos");
      SocketClose(socket_handle);
      return "";
     }

   Print("Datos enviados con éxito. Bytes enviados: ", bytesSent);

   uchar recv_buffer[1024];
   string received_data = "";
   uint timeout = 5000; // 5 segundos de tiempo de espera
   uint start_time = GetTickCount();

   while(GetTickCount() - start_time < timeout)
     {
      int received_bytes = SocketRead(socket_handle, recv_buffer, ArraySize(recv_buffer), 100);
      if(received_bytes > 0)
        {
         Print("Bytes recibidos: ", received_bytes);
         received_data += CharArrayToString(recv_buffer, 0, received_bytes);
         Print("Datos parciales recibidos: ", received_data);
         break; // Exit the loop after data is received
        }
      else if(received_bytes == 0)
        {
         Sleep(10);
        }
      else
        {
         int error = GetLastError();
         Print("Error al recibir datos. Código de error: ", error);
         if(error != 4014) break;
        }
     }

   SocketClose(socket_handle);

   if(received_data == "")
     {
      Print("No se recibieron datos del servidor Python");
      return "";
     }

   Print("Datos recibidos con éxito: ", received_data);
   return received_data;
  }

//+------------------------------------------------------------------+
// Helper function to convert uchar array to string
string CharArrayToString(const uchar &arr[], int start, int length)
  {
   string result;
   char temp[];
   ArrayResize(temp, length);
   ArrayCopy(temp, arr, 0, start, length);
   result = CharArrayToString(temp);
   return result;
  }
//+------------------------------------------------------------------+


and this is the py script server.py

import socket

def start_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('127.0.0.1', 65432))
    server_socket.listen(1)
    print("Servidor Python iniciado y esperando conexiones...")

    while True:
        client_socket, addr = server_socket.accept()
        print(f"Conexión desde {addr}")
        
        try:
            data = client_socket.recv(1024).decode()
            print(f"Datos recibidos: {data}")

            result = process_data(data)
            client_socket.sendall(result.encode())
            print(f"Respuesta enviada al cliente: {result}")
        except Exception as e:
            print(f"Error en la comunicación: {e}")
        finally:
            client_socket.shutdown(socket.SHUT_RDWR)
            client_socket.close()
            print("Conexión cerrada")

def process_data(data):
    result = f"Resultado procesado de: {data}"
    print(f"Datos procesados. Resultado: {result}")
    return result

if __name__ == "__main__":
    start_server()


Please, I'm new to Sockets, can some one tell me what's wrong and how to make it work?

 
//+------------------------------------------------------------------+
//| Función para enviar y recibir datos                              |
//+------------------------------------------------------------------+
string CommunicateWithPython(string data)
  {
   int socket_handle = InitSocket();
   if(socket_handle < 0)
      return "";

   uchar send_buffer[];
   StringToCharArray(data, send_buffer);
   int bytesSent = SocketSend(socket_handle, send_buffer, ArraySize(send_buffer));
   if(bytesSent < 0)
     {
      Print("Error sending data!");
      SocketClose(socket_handle);
      return "";
     }

   Print("data sent: ", bytesSent);


   uint timeout = 5000; // 5 segundos de tiempo de espera

   uchar   rsp[]; 
   string result; 
   uint   timeout_check=GetTickCount()+timeout; 
//--- read data from sockets till they are still present but not longer than timeout 
   do 
     { 
      uint len=SocketIsReadable(socket_handle); 
      if(len) 
        { 
         int rsp_len; 
         //--- various reading commands depending on whether the connection is secure or not 
         rsp_len=SocketRead(socket_handle,rsp,len,timeout); 
         //--- analyze the response 
         if(rsp_len>0) 
           { 
            result+=CharArrayToString(rsp,0,rsp_len); 
           } 
        } 
     } 
   while(GetTickCount()<timeout_check && !IsStopped()); 
   SocketClose(socket_handle);

   if(result == "")
     {
      Print("no data from pthogn");
      return "";
     }

   Print("data from python received: ", result);
   return result;
  }
 
Yashar Seyyedin #:
string CommunicateWithPython(string data)   {    int socket_handle = InitSocket();    if(socket_handle < 0)       return "";    uchar send_buffer[];    StringToCharArray(data, send_buffer);    int bytesSent = SocketSend(socket_handle, send_buffer, ArraySize(send_buffer));    if(bytesSent < 0)      {       Print("Error sending data!");       SocketClose(socket_handle);       return "";      }    Print("data sent: ", bytesSent);    uint timeout = 5000; // 5 segundos de tiempo de espera    uchar   rsp[];    string result;    uint   timeout_check=GetTickCount()+timeout; //--- read data from sockets till they are still present but not longer than timeout    do      {       uint len=SocketIsReadable(socket_handle);       if(len)         {          int rsp_len;          //--- various reading commands depending on whether the connection is secure or not          rsp_len=SocketRead(socket_handle,rsp,len,timeout);          //--- analyze the response          if(rsp_len>0)            {             result+=CharArrayToString(rsp,0,rsp_len);            }         }      }    while(GetTickCount()<timeout_check && !IsStopped());    SocketClose(socket_handle);    if(result == "")      {       Print("no data from pthogn");       return "";      }    Print("data from python received: ", result);    return result;   }

Thanks! you made me not loose more time.