SocketTlsReadAvailable

Kullanılabilir tüm verileri güvenli TLS bağlantısından okur.

int  SocketTlsReadAvailable(
   int           socket,               // soket
   uchar&        buffer[],             // soketten veri okumak için tampon
   const uint    buffer_maxlen         // okunacak bayt sayısı
   );

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.

buffer

[out]  Veri okunan uchar dizisine referans. Dinamik dizi boyutu, okunan bayt sayısıyla artar. Dizi boyutu, INT_MAX (2147483647) değerini aşamaz.

buffer_maxlen

[in]  buffer[] dizisine okunacak bayt sayısı. Diziye sığmayan veriler sokette kalır. Bu veriler bir sonraki SocketTlsReadAvailable veya SocketTlsRead çağrısı tarafından alınabilirler. buffer_maxlen, INT_MAX (2147483647) değerini aşamaz.

Geri dönüş değeri

Başarılı olursa, okuma baytlarının sayısı geri döner. Bir hata durumunda, 0 geri döner.

Not

Fonksiyon yürütülürken bir sistem soketinde bir hata oluşursa, SocketConnect aracılığıyla kurulan bağlantı kesilir.

Veri okuma hatası olması durumunda; hata 5273 (ERR_NETSOCKET_IO_ERROR), _LastError'a yazılır.

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:

//+------------------------------------------------------------------+
//|                                       SocketTlsReadAvailable.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 script_show_inputs
//+------------------------------------------------------------------+
//| Komut dosyası girdileri                                          |
//+------------------------------------------------------------------+
input string InpMethod ="GET";            // Yöntem (HEAD,GET)
input string InpServer ="www.google.com"// Sunucu
input uint   InpPort   =443;              // Port
input uint   InpTimeout=5000;             // Zaman aşımı
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart(void)
  {
   Print("Server: ",InpServer);
   Print("Port: ",InpPort);
//--- bir soket oluştur ve tanıtıcısını al
   const int socket=SocketCreate();
 
   if(socket==INVALID_HANDLE)
     {
      Print("SocketCreate() failed. Error ",GetLastError());
      return;
     }
//--- bir soket sistem nesnesi için veri alma ve gönderme zaman aşımlarını ayarla
   if(!SocketTimeouts(socket,InpTimeout,InpTimeout))
     {
      PrintFormat("SocketTimeouts(%u, %u) failed. Error %d",InpTimeout,InpTimeout,GetLastError());
      SocketClose(socket);
      return;
     }
//--- port üzerinden sunucuya bağlan
   if(!SocketConnect(socket,InpServer,InpPort,InpTimeout))
     {
      PrintFormat("SocketConnect('%s', %u, %u) failed. Error %d",InpServer,InpPort,InpTimeout,GetLastError());
      SocketClose(socket);
      return;
     }
//--- ağ bağlantısını güvenli hale getirmek için kullanılan sertifika hakkında veri al
   string   subject,issuer,serial,thumbprint;
   datetime expiration;
 
   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);
     }
   else
     {
      //--- sunucu bir sertifika sağlamıyorsa - güvenli olmayan bir bağlantı olduğunu bildir ve ayrıl
      Print("The connection is not secured by a certificate");
      SocketClose(socket);
      return;
     }
//--- sunucuya bir istek gönder
   string request=StringFormat("%s / HTTP/1.1\r\nHost: %s\r\nUser-Agent: MetaTrader 5\r\n\r\n",InpMethod,InpServer);
 
   if(HTTPSendTLS(socket,request))
     {
      //--- istek gönderildi - yanıt al
      Print("\nRequest sent. Starting page loading...");
      uchar response[]; // alınan tüm veriler (belge başlığı ve gövdesi)
 
      if(!HTTPRecvTLS(socket,response,InpTimeout))
        {
         Print("There were errors while reading the page");
         SocketClose(socket);
         return;
        }
      //--- alınan veri baytı miktarını rapor et
      PrintFormat("%u bytes received",response.Size());
      //--- yalnızca elde edilen sayfa başlığını görüntüle
      string result    =CharArrayToString(response,0,WHOLE_ARRAY,CP_UTF8);
      int    header_end=StringFind(result,"\r\n\r\n");
 
      if(header_end>0)
        {
         Print("\nHTTP answer header received:");
         Print(StringSubstr(result,0,header_end));
        }
     }
//--- kullanımdan sonra soketi kapat
   SocketClose(socket);
   /*
   sonuç:
   Serverwww.google.com
   Port443
   TLS certificate:
      Owner: /CN=www.google.com
      Issuer: /C=US/O=Google Trust Services/CN=WR2
      Number0d:43:b1:4a:bb:9c:15:96:10:e1:3d:55:23:9f:25:4e
      Print89167618e5017f813aff981c88ce422dc1016bdf
      Expiration2024.12.30 08:26:35
 
   Request sentStarting page loading...
   HTTPRecvTLSDocument received within 27 attempts
   25185 bytes received
 
   HTTP answer header received:
   HTTP/1.1 200 OK
   DateFri25 Oct 2024 17:12:42 GMT
   Expires: -1
   Cache-Controlprivatemax-age=0
   Content-Typetext/htmlcharset=ISO-8859-1
   Content-Security-Policy-Report-Onlyobject-src 'none';base-uri 'self';script-src 'nonce-CUL2rdUOeAN7xIV6v0WUuQ' 'strict-dynamic' 'report-sample' 'unsafe-eval' 'unsafe-inlinehttpshttp:;report-uri https://csp.withgoogle.com/csp/gws/other-hp
   Accept-CHSec-CH-Prefers-Color-Scheme
   P3PCP="This is not a P3P policy! See g.co/p3phelp for more info."
   Servergws
   X-XSS-Protection0
   X-Frame-OptionsSAMEORIGIN
   Set-CookieAEC=AVYB7coyYMCdweTDTaWeGYzmRnxzKGqsOEosH_VkbCn8xhWkFz6v0kxQFwexpires=Wed23-Apr-2025 17:12:42 GMTpath=/; domain=.google.comSecureHttpOnlySameSite=lax
   Set-CookieNID=518=J02X02Ff4v_9sMcNoUz-1SolmuG08E26Gs438ik0J_SOJUMy7of-P-qup-LaNSWVXUL8OjhOXpGIGuJQGIoEPBnzqDKCH-46_FN4J2foHeWTlGG8bVVvQ44AHWLg1OXjrGp3CUBexYdczLWNy3LxEcb7eh6mxSvFzOelPC6-vpXkaumLQ80x9gF_RpLcAYfN4ehTexpires=Sat26-Apr-2025 17:12:42 GMTpath=/; domain=.google.comHttpOnly
   Alt-Svch3=":443"ma=2592000,h3-29=":443"ma=2592000
   Accept-Rangesnone
   VaryAccept-Encoding
   Transfer-Encodingchunked
   */
  }
//+------------------------------------------------------------------+
//| Güvenli bir bağlantı üzerinden HTTP isteği gönder                |
//+------------------------------------------------------------------+
bool HTTPSendTLS(int socket,const string request)
  {
//--- dizgeyi bir karakter dizisine dönüştür, sondaki sıfırı at
   char req[];
   int  len=StringToCharArray(request,req,0,WHOLE_ARRAY,CP_UTF8)-1;
 
   if(len<0)
      return false;
 
   return(SocketTlsSend(socket,req,len)==len);
  }
//+------------------------------------------------------------------+
//| Güvenli bir bağlantı üzerinden bir web sayfası al                |
//+------------------------------------------------------------------+
bool HTTPRecvTLS(int socket,uchar &response[],const uint timeout_ms)
  {
//--- zaman aşımı süresi dolmadan önce güvenli TLS bağlantısından mevcut verileri oku
   ulong timeout_check=GetTickCount64()+timeout_ms;
   uchar block[1024];   // soketten blok veri okumak için arabellek
   uint  attempt=0;     // istenen veri bloğu sayısı
   int   err    =0;     // hata kodu
 
   ResetLastError();
 
   do
     {
      //--- bloklar halinde oku, maksimum 1024 bayt
      int len=SocketTlsReadAvailable(socket,block,1024);
 
      if(len>0)
        {
         attempt++;
         //--- elde edilen veri bloklarını birleştir
         ArrayCopy(response,block,response.Size());
         //--- elde edilen verileri analiz et, başlık, sayfa gövdesi, bitiş veya yükleme hatası vb. tanımla
         //...
         //...
         //...
         timeout_check=GetTickCount64()+timeout_ms;
        }
      else
         Sleep(10);
 
      err=GetLastError();
     }
   while(!IsStopped() && GetTickCount()<timeout_check && !err);
//--- okuma sırasında herhangi bir hata oldu mu?
   if(err)
     {
      Print("Error ",err);
      return(false);
     }
 
   PrintFormat("%s: Document received within %d attempts",__FUNCTION__,attempt);
   return(true);
  }

Ayrıca bakınız

SocketTimeouts, MathSwap