SocketIsWritable

Comprueba si es posible registrar datos en el socket en el momento actual.

bool  SocketIsWritable(
   const int  socket      // manejador del socket
   );

Parámetros

socket

[in]  Manejador del socket retornado por la función SocketCreate. Al transmitir un manejador incorrecto, en _LastError se registra el error 5270 (ERR_NETSOCKET_INVALIDHANDLE).

Valor retornado

Retorna true si el registro es posible, de lo contrario,false.

Observación

Al usar esta función, usted podrá comprobar si es posible registrar datos en el socket ahora mismo.

Si al ejecutar esta función aparece un error en el socket de sistema, la conexión establecida a través de SocketConnect será interrumpida.

Solo se puede llamar la función desde los expertos y scripts, puesto que funcionan en su propio flujo de ejecución. Si se llama desde el indicador, GetLastError() retornará el error 4014 — "La función de sistema no está permitida para la llamada".

Ejemplo:

//+------------------------------------------------------------------+
//|                                             SocketIsWritable.mq5 |
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com
#property version     "1.00"
#property description "Add Address to the list of allowed ones in the terminal settings to let the example work"
#property script_show_inputs
 
input string Address    ="www.mql5.com";
input int    Port       =80;
bool         ExtTLS =false;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart(void)
  {
//--- creamos un socket y obtenemos su handle
   int socket=SocketCreate();
//--- проверим хэндл
   if(socket!=INVALID_HANDLE)
     {
      //--- si todo está en orden, nos conectamos
      if(SocketConnect(socket,Address,Port,1000))
        {
         PrintFormat("Established connection to %s:%d",Address,Port);
 
         string   subject,issuer,serial,thumbprint;
         datetime expiration;
         //--- si la conexión está protegida por un certificado, mostraremos sus datos
         if(SocketTlsCertificate(socket,subject,issuer,serial,thumbprint,expiration))
           {
            Print("TLS certificate:");
            Print("   Owner:      ",subject);
            Print("   Issuer:     ",issuer);
            Print("   Number:     ",serial);
            Print("   Print:      ",thumbprint);
            Print("   Expiration: ",expiration);
            ExtTLS=true;
           }
         //--- enviamos al servidor una solicitud GET
         if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r\n\r\n"))
           {
            Print("GET request sent");
            //--- leemos la respuesta
            if(!HTTPRecv(socket,1000))
               Print("Failed to get a response, error ",GetLastError());
           }
         else
            Print("Failed to send GET request, error ",GetLastError());
        }
      else
        {
         PrintFormat("Connection to %s:%d failed, error %d",Address,Port,GetLastError());
        }
      //--- imprimimos en el registro la posibilidad de escribir datos en el socket en el momento actual
      if(SocketIsWritable(socket))
         Print("At the current moment in time, writing data to the socket is possible");
      else
         Print("It is not possible to write data to the socket at the current time");
      //--- cerramos el socket después del uso
      if(SocketClose(socket))
         Print("Now the socket is closed");
     }
   else
      Print("Failed to create a socket, error ",GetLastError());
   /*
   resultado:
   At the current moment in timewriting data to the socket is possible
   Socket is closed now
   */
  }
//+------------------------------------------------------------------+
//| Enviando comando al servidor                                     |
//+------------------------------------------------------------------+
bool HTTPSend(int socket,string request)
  {
//--- convertimos la cadena en un array de caracteres, el cero final se descartará
   char req[];
   int  len=StringToCharArray(request,req)-1;
 
   if(len<0)
      return(false);
//--- si se utiliza una conexión protegida por TLS a través del puerto 443
   if(ExtTLS)
      return(SocketTlsSend(socket,req,len)==len);
//--- si se utiliza una conexión TCP normal
   return(SocketSend(socket,req,len)==len);
  }
//+------------------------------------------------------------------+
//| Leyendo la respuesta del servidor                                |
//+------------------------------------------------------------------+
bool HTTPRecv(int socket,uint timeout_ms)
  {
   char   rsp[];
   string result;
   ulong  timeout_check=GetTickCount64()+timeout_ms;
//--- leemos los datos del socket mientras esté disponible, pero sin superar el timeout
   do
     {
      uint len=SocketIsReadable(socket);
 
      if(len)
        {
         int rsp_len;
         //--- diferentes comandos de lectura dependiendo de si la conexión es segura o no
         if(ExtTLS)
            rsp_len=SocketTlsRead(socket,rsp,len);
         else
            rsp_len=SocketRead(socket,rsp,len,timeout_ms);
         //--- разберем ответ
         if(rsp_len>0)
           {
            result+=CharArrayToString(rsp,0,rsp_len);
            //--- imprimimos solo el encabezado de la respuesta
            int header_end=StringFind(result,"\r\n\r\n");
 
            if(header_end>0)
              {
               Print("HTTP answer header received:");
               Print(StringSubstr(result,0,header_end));
               return(true);
              }
            //--- actualizamos el tiempo de timeout de la lectura
            timeout_check=GetTickCount64()+timeout_ms;
           }
        }
     }
   while(GetTickCount64()<timeout_check && !IsStopped());
 
   return(false);
  }