//+------------------------------------------------------------------+ //| 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) { //--- criamos um soquete e obtemos seu identificador int socket=SocketCreate(); //--- verificamos o identificador if(socket!=INVALID_HANDLE) { //--- se tudo estiver bem, podemos nos conectar. if(SocketConnect(socket,Address,Port,1000)) { PrintFormat("Established connection to %s:%d",Address,Port); string subject,issuer,serial,thumbprint; datetime expiration; //--- se a conexão estiver protegida por um certificado, imprimimos seus dados 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; } //--- enviamos uma solicitação GET ao servidor if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\nUser-Agent: MT5\r\n\r\n")) { Print("GET request sent"); //--- lemos a resposta 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 o sinalizador estiver definido, fechamos o soquete após o uso if(CloseSocket) SocketClose(socket); } else Print("Failed to create a socket, error ",GetLastError()); //--- verificamos a conexão ao servidor bool connected=SocketIsConnected(socket); //--- se não houver conexão, encerramos if(!connected) { Print("No connection to server"); } //--- если есть подклюse houver uma conexão com o servidor else { Print("Connection to the server is available\nThe connection needs to be closed. Closing"); //--- encerramos o soquete e verificamos o status da conexão novamente SocketClose(socket); connected=SocketIsConnected(socket); } //--- imprimimos o estado atual da conexão com o servidor no log Print("Currently connected: ",(connected ? "opened" : "closed")); /* resultado quando CloseSocket = true: No connection to server Currently connected: closed resultado quanto CloseSocket = false: Connection to the server is available The connection needs to be closed. Closing Currently connected: closed */ } //+------------------------------------------------------------------+ //| Envio de um comando ao servidor | //+------------------------------------------------------------------+ bool HTTPSend(int socket,string request) { //--- convertemos a string em um array de caracteres, descartando o zero final char req[]; int len=StringToCharArray(request,req)-1; if(len<0) return(false); //--- se for usada uma conexão protegida por TLS via porta 443 if(ExtTLS) return(SocketTlsSend(socket,req,len)==len); //--- se for usada uma conexão TCP normal return(SocketSend(socket,req,len)==len); } //+------------------------------------------------------------------+ //| Leitura da resposta do servidor | //+------------------------------------------------------------------+ bool HTTPRecv(int socket,uint timeout_ms) { char rsp[]; string result; ulong timeout_check=GetTickCount64()+timeout_ms; //--- lemos dados do soquete enquanto eles existirem, mas não mais do que o tempo limite do { uint len=SocketIsReadable(socket); if(len) { int rsp_len; //--- comandos de leitura diferentes, dependendo do fato de a conexão estar protegida ou não if(ExtTLS) rsp_len=SocketTlsRead(socket,rsp,len); else rsp_len=SocketRead(socket,rsp,len,timeout_ms); //--- analisamos a resposta if(rsp_len>0) { result+=CharArrayToString(rsp,0,rsp_len); //--- imprimimos apenas o cabeçalho da resposta 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); } //--- atualizamos o tempo de expiração do tempo limite de leitura timeout_check=GetTickCount64()+timeout_ms; } } } while(GetTickCount64()<timeout_check && !IsStopped()); return(false); } |