SocketIsReadable

소켓에서 읽을 수 있는 바이트 수를 가져옵니다.

uint  SocketIsReadable(
   const int  socket      // 소켓 처리
   );

Parameter

socket

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

반환값

읽을 수 있는 바이트 수입니다. 오류가 발생하면 0이 반환됩니다.

참고

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

SocketRead호출 전에, 소켓에 판독할 데이터가 있는지 확인합니다. 그렇지 않으면 데이터가 없는 경우 SocketRead 함수는 프로그램 실행을 지연시키는 timeout_ms 내의 데이터를 기다립니다.

이 함수는 자체 실행 스레드에서 실행되므로 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());
  }
//+------------------------------------------------------------------+