SocketTlsRead

보안 TLS 연결에서 데이터를 읽습니다.

int  SocketTlsRead(
   int           socket,               // 소켓
   uchar&        buffer[],             // 소켓에서 데이터를 읽기 위한 버퍼
   uint          buffer_maxlen         // 읽을 바이트 수
   );

Parameter

socket

[in]  소켓 핸들이 SocketCreate 함수에 의해 반환됩니다. 잘못되 핸들이 _LastError로 전달될 시, 5270 에러(ERR_NETSOCKET_INVALIDHANDLE)가 활성화됩니다.

buffer

[out]  데이터를 읽을 수 있는 uchar 유형 배열에 대한 레퍼런스입니다. 동적 배열 크기가 읽기 바이트 수만큼 증가합니다. 배열의 크기는 INT_MAX (2147483647)을 초과할 수 없습니다.

buffer_maxlen

[in] buffer[] 배열에 읽을 바이트 수. 배열에 맞지 않는 데이터는 소켓에 남아 있습니다. 그것들은 다음 SocketTLSRead 호출을 통해 받을 수 있습니다. buffer_maxlenINT_MAX (2147483647)를 초과할 수 없습니다.

반환값

성공적이면 읽기 바이트 수를 반환합니다. 오류인 경우, -1이 반환됩니다.

참고

함수 실행시 시스템 소켓에 오류가 발생하면, SocketConnect을 통해 설정된 연결이 중단됩니다.

지정된 양의 데이터를 수신하거나 타임아웃이 (SocketTimeouts)에 도달할 때까지 함수가 실행됩니다.

데이터 읽기 오류가 발생시, 5273 에러(ERR_NETSOCKET_IO_ERROR)가 _LastError에 기록됩니다.

이 함수는 자체 실행 스레드에서 실행되므로 Expert Advisor 및 스크립트에서만 호출할 수 있습니다. 지표에서 호출하는 경우, GetLastError() 는 4014 에러– "호출이 허용되지 않는 함수입니다."가 반환됩니다.

예:

//+------------------------------------------------------------------+
//|                                                SocketExample.mq5 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright   "Copyright 2000-2024, MetaQuotes Ltd."
#property link        "https://www.mql5.com"
#property version     "1.00"
#property description "터미널 설정에서 허용된 주소 목록에 주소를 추가하여 예제가 작동하도록 합니다."
#property script_show_inputs
 
input string Address="www.mql5.com";
input int    Port   =80;
bool         ExtTLS =false;
//+------------------------------------------------------------------+
//| 서버로 명령 전송                                       |
//+------------------------------------------------------------------+
bool HTTPSend(int socket,string request)
  {
   char req[];
   int  len=StringToCharArray(request,req)-1;
   if(len<0)
      return(false);
//--- 포트 443을 통해 보안 TLS 연결을 사용하는 경우
   if(ExtTLS)
      return(SocketTlsSend(socket,req,len)==len);
//--- 표준 TCP 연결을 사용하는 경우
   return(SocketSend(socket,req,len)==len);
  }
//+------------------------------------------------------------------+
//| 서버 응답을 읽습니다                                             |
//+------------------------------------------------------------------+
bool HTTPRecv(int socket,uint timeout)
  {
   char   rsp[];
   string result;
   uint   timeout_check=GetTickCount()+timeout;
//--- 소켓이 여전히 존재하지만 제한 시간보다 길지 않을 때까지 소켓에서 데이터를 읽습니다
   do
     {
      uint len=SocketIsReadable(socket);
      if(len)
        {
         int rsp_len;
         //--- 연결의 보안 여부에 따라 다양한 읽기 명령
         if(ExtTLS)
            rsp_len=SocketTlsRead(socket,rsp,len);
         else
            rsp_len=SocketRead(socket,rsp,len,timeout);
         //--- 반응을 분석합니다
         if(rsp_len>0)
           {
            result+=CharArrayToString(rsp,0,rsp_len);
            //--- 응답 헤더만 출력합니다
            int header_end=StringFind(result,"\r\n\r\n");
            if(header_end>0)
              {
               Print("HTTP 응답 헤더 수신:");
               Print(StringSubstr(result,0,header_end));
               return(true);
              }
           }
        }
     }
   while(GetTickCount()<timeout_check && !IsStopped());
   return(false);
  }
//+------------------------------------------------------------------+
//| 스크립트 프로그램 시작 함수                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   int socket=SocketCreate();
//--- 핸들 체크
   if(socket!=INVALID_HANDLE)
     {
      //--- 모든 것이 문제 없다면 연결합니다
      if(SocketConnect(socket,Address,Port,1000))
        {
         Print("다음에 대한 연결 설정 ",주소,":",포트);
 
         string   subject,issuer,serial,thumbprint;
         datetime expiration;
         //--- 인증서로 연결이 보안된 경우 해당 데이터를 표시합니다
         if(SocketTlsCertificate(socket,subject,issuer,serial,thumbprint,expiration))
           {
            Print("TLS 인증서:");
            Print("   소유자:  ",subject);
            Print("   발행인:  ",issuer);
            Print("   숫자:     ",serial);
            Print("   Print: ",thumbprint;
            Print("   만료: ",expiration;
            ExtTLS=true;
           }
         //--- GET 요청을 서버로 전송합니다
         if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r\n\r\n"))
           {
            Print("GET 요청 발송됨");
            //--- 반응을 읽습니다
            if(!HTTPRecv(socket,1000))
               Print("응답 가져오기 실패, error ",GetLastError());
           }
         else
            Print("응답 가져오기 실패, error ",GetLastError());
        }
      else
        {
         Print("다음에 연결 ",주소,":",포트," 실패, error ",GetLastError());
        }
      //--- 이용 후 소켓을 닫습니다
      SocketClose(socket);
     }
   else
      Print("소켓 생성 실패, error ",GetLastError());
  }
//+------------------------------------------------------------------+

참고 항목

SocketTimeouts, MathSwap