SocketIsConnected

Soketin şu anda bağlı olup olmadığını kontrol eder.

bool  SocketIsConnected(
   const int  socket      // soket tanıtıcı değeri
   );

Parametreler

socket

[in] SocketCreate() fonksiyonu tarafından geri döndürülen soket tanıtıcı değeri. _LastError'a yanlış bir tanıtıcı değeri iletildiğinde, 5270 hatası (ERR_NETSOCKET_INVALIDHANDLE) etkinleştirilir.

Geri dönüş değeri

Soket bağlıysa true, aksi halde false olarak geri döner.

Not

SocketIsConnected() fonksiyonu mevcut soket bağlantı durumunun kontrol edilmesini sağlar.

Fonksiyon, yalnızca kendi yürütme iş parçacıklarında çalışan Uzman Danışmanlardan ve komut dosyalarından çağrılabilir. Bir göstergeden çağrılırsa; GetLastError(), 4014 hatasını geri döndürür - "Çağırma için fonksiyona izin verilmiyor".

Örnek:

//+------------------------------------------------------------------+
//|                                            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)
  {
//--- bir soket oluştur ve tanıtıcısını al
   int socket=SocketCreate();
//--- tanıtıcıyı kontrol et
   if(socket!=INVALID_HANDLE)
     {
      //--- her şey yolundaysa, bağlan
      if(SocketConnect(socket,Address,Port,1000))
        {
         PrintFormat("Established connection to %s:%d",Address,Port);
 
         string   subject,issuer,serial,thumbprint;
         datetime expiration;
         //--- bağlantı sertifika ile korunuyorsa, verilerini görüntüle
         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;
           }
         //--- sunucuya GET isteği gönder
         if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r\n\r\n"))
           {
            Print("GET request sent");
            //--- yanıtı oku
            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());
        }
      //--- bayrak ayarlanmışsa, kullanımdan sonra soketi kapat
      if(CloseSocket)
         SocketClose(socket);
     }
   else
      Print("Failed to create a socket, error ",GetLastError());
 
//--- sunucu bağlantısını kontrol et
   bool connected=SocketIsConnected(socket);
//--- bağlantı yoksa işlemi sonlandır
   if(!connected)
     {
      Print("No connection to server");
     }
//--- sunucu bağlantısı mevcutsa
   else
     {
      Print("Connection to the server is available\nThe connection needs to be closed. Closing");
      //--- soketi kapat ve bağlantı durumunu tekrar kontrol et
      SocketClose(socket);
      connected=SocketIsConnected(socket);
     }
 
//--- mevcut sunucu bağlantı durumunu görüntüle
   Print("Currently connected: ",(connected ? "opened" : "closed"));
   /*
   CloseSocket = true durumunda sonuç:
   No connection to server
   Currently connectedclosed
 
   CloseSocket = false durumunda sonuç:
   Connection to the server is available
   The connection needs to be closedClosing
   Currently connectedclosed
   */
  }
//+------------------------------------------------------------------+
//| Sunucuya komut gönder                                            |
//+------------------------------------------------------------------+
bool HTTPSend(int socket,string request)
  {
//--- dizgeyi bir karakter dizisine dönüştür, sondaki sıfırı at
   char req[];
   int  len=StringToCharArray(request,req)-1;
 
   if(len<0)
      return(false);
//--- 443 portu üzerinden güvenli bir TLS bağlantısı kullanılıyorsa
   if(ExtTLS)
      return(SocketTlsSend(socket,req,len)==len);
//--- normal bir TCP bağlantısı kullanılıyorsa
   return(SocketSend(socket,req,len)==len);
  }
//+------------------------------------------------------------------+
//| Sunucu yanıtını oku                                              |
//+------------------------------------------------------------------+
bool HTTPRecv(int socket,uint timeout_ms)
  {
   char   rsp[];
   string result;
   ulong  timeout_check=GetTickCount64()+timeout_ms;
//--- zaman aşımından daha uzun olmamak kaydıyla kullanılabilir durumdayken soketten veri oku
   do
     {
      uint len=SocketIsReadable(socket);
 
      if(len)
        {
         int rsp_len;
         //--- bağlantının güvenli olup olmadığına bağlı olarak farklı okuma komutları
         if(ExtTLS)
            rsp_len=SocketTlsRead(socket,rsp,len);
         else
            rsp_len=SocketRead(socket,rsp,len,timeout_ms);
         //--- yanıtı ayrıştır
         if(rsp_len>0)
           {
            result+=CharArrayToString(rsp,0,rsp_len);
            //--- yalnızca yanıt başlığını görüntüle
            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);
              }
            //--- okuma zaman aşımı sona erme zamanını güncelle
            timeout_check=GetTickCount64()+timeout_ms;
           }
        }
     }
   while(GetTickCount64()<timeout_check && !IsStopped());
 
   return(false);
  }

Ayrıca bakınız

SocketConnect, SocketIsWritable, SocketCreate, SocketClose