SocketIsConnected

Controlla se il socket è attualmente connesso.

bool  SocketIsConnected(
   const int  socket      // handle del socket
   );

Parametri

socket

[in]  Handle del socket restituito dalla funzione SocketCreate(). Quando viene passato un handle errato _LastError, si attiva l'errore 5270 (ERR_NETSOCKET_INVALIDHANDLE).

Valore di Ritorno

Restituisce true se il socket è connesso, altrimenti - false.

Nota

La funzione SocketIsConnected() consente di verificare lo stato corrente della connessione socket.

La funzione può essere chiamata solo da Expert Advisors e scripts, poiché vengono eseguiti nei relativi thread di esecuzione. Se si chiama da un indicatore, GetLastError() restituisce l'errore 4014 - "Function is not allowed for call (la funzione non è consentita per la chiamata)".

Esempio:

//+------------------------------------------------------------------+
//|                                            SocketIsConnected.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;
input bool   CloseSocket=true;
bool         ExtTLS     =false;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart(void)
  {
//--- creare un socket e ottenere il suo handle (gestore)
   int socket=SocketCreate();
//--- controllare l'handle
   if(socket!=INVALID_HANDLE)
     {
 //--- se tutto va bene, connettere
      if(SocketConnect(socket,Address,Port,1000))
        {
         PrintFormat("Established connection to %s:%d",Address,Port);
 
         string   subject,issuer,serial,thumbprint;
         datetime expiration;
 //--- se la connessione è protetta da un certificato, visualizzare i dati di tale certificato
         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;
           }
 //--- inviare la richiesta GET al server
         if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r\n\r\n"))
           {
            Print("GET request sent");
 //--- leggere la risposta
            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());
        }
 //--- se il flag è impostato, chiudere il socket dopo l'uso
      if(CloseSocket)
         SocketClose(socket);
     }
   else
      Print("Failed to create a socket, error ",GetLastError());
 
//--- verificare la connessione al server
   bool connected=SocketIsConnected(socket);
//--- terminare l'operazione se non c'è connessione
   if(!connected)
     {
      Print("No connection to server");
     }
//--- se è presente una connessione al server
   else
     {
      Print("Connection to the server is available\nThe connection needs to be closed. Closing");
 //--- chiudere il socket e controllare lo stato della connessione di nuovo
      SocketClose(socket);
      connected=SocketIsConnected(socket);
     }
 
//--- visualizzare l'attuale stato della connessione al server
   Print("Currently connected: ",(connected ? "opened" : "closed"));
   /*
   result in case CloseSocket = true:
   No connection to server
   Currently connectedclosed
 
   result in case CloseSocket = false:
   Connection to the server is available
   The connection needs to be closedClosing
   Currently connectedclosed
   */
  }
//+------------------------------------------------------------------+
//| Comando di invio al server                                       |
//+------------------------------------------------------------------+
bool HTTPSend(int socket,string request)
  {
//--- convertire la stringa in un array di caratteri, scartare lo zero finale
   char req[];
   int  len=StringToCharArray(request,req)-1;
 
   if(len<0)
      return(false);
//--- se viene utilizzata una connessione TLS sicura tramite la porta 443
   if(ExtTLS)
      return(SocketTlsSend(socket,req,len)==len);
//--- se si utilizza una connessione TCP normale
   return(SocketSend(socket,req,len)==len);
  }
//+------------------------------------------------------------------+
//| Leggere la risposta del server                                   |
//+------------------------------------------------------------------+
bool HTTPRecv(int socket,uint timeout_ms)
  {
   char   rsp[];
   string result;
   ulong  timeout_check=GetTickCount64()+timeout_ms;
//--- leggere i dati dal socket mentre c'è, ma non più del timeout
   do
     {
      uint len=SocketIsReadable(socket);
 
      if(len)
        {
         int rsp_len;
 //--- diversi comandi di lettura a seconda che la connessione sia sicura o meno
         if(ExtTLS)
            rsp_len=SocketTlsRead(socket,rsp,len);
         else
            rsp_len=SocketRead(socket,rsp,len,timeout_ms);
 //--- risposta dell'analisi
         if(rsp_len>0)
           {
            result+=CharArrayToString(rsp,0,rsp_len);
 //--- visualizzare solo l'header della risposta
            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);
              }
 //--- aggiornamento del tempo di scadenza di lettura
            timeout_check=GetTickCount64()+timeout_ms;
           }
        }
     }
   while(GetTickCount64()<timeout_check && !IsStopped());
 
   return(false);
  }

Guarda anche

SocketConnect, SocketIsWritable, SocketCreate, SocketClose