从mql5连接到websocket节点js服务器

时间:2019-08-03 06:19:39

标签: websocket mql5

我编写了用于连接webSocket和的MQL5代码 我得到
 Connection to ws://127.0.0.1:8080 failed, error 4014
我的出口何时开始; 我将节点js和websocket("^1.0.29")用于Web套接字服务器; 在文档中为此link编写 该函数只能在EA脚本和脚本中运行,因为它们在自己的执行线程中运行。如果从指示器进行调用,GetLastError()返回错误4014 – 不允许调用该功能。但是我在专家中使用了此功能,并将此文件包含到主要的专家文件中。

const WebSocketServer = require('websocket').server;
const http = require('http');
//-----------------------------socket-------------------------------
let server = http.createServer(function (request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function () {
    console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});
function originIsAllowed(origin) {
    // put logic here to detect whether the specified origin is allowed.
    return true;
}
wsServer.on('request', function (request) {
    if (!originIsAllowed(request.origin)) {
        // Make sure we only accept requests from an allowed origin
        request.reject();
        console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
        return;
    }
    let connection = request.accept('', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function (message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        } else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function (reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});
#property copyright   "Copyright 2018, MetaQuotes Software Corp." 
#property link        "ws://127.0.0.1" 
#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="ws://127.0.0.1"; 
input int    Port   =8080; 
bool         ExtTLS =false; 
//+------------------------------------------------------------------+ 
//| Send command to the server                                       | 
//+------------------------------------------------------------------+ 
bool HTTPSend(int socket,string request) 
  { 
   char req[]; 
   int  len=StringToCharArray(request,req)-1; 
   if(len<0) 
      return(false); 
//--- if secure TLS connection is used via the port 443 
   if(ExtTLS) 
      return(SocketTlsSend(socket,req,len)==len); 
//--- if standard TCP connection is used 
   return(SocketSend(socket,req,len)==len); 
  } 
//+------------------------------------------------------------------+ 
//| Read server response                                             | 
//+------------------------------------------------------------------+ 
bool HTTPRecv(int socket,uint timeout) 
  { 
   char   rsp[]; 
   string result; 
   uint   timeout_check=GetTickCount()+timeout; 
//--- read data from sockets till they are still present but not longer than timeout 
   do 
     { 
      uint len=SocketIsReadable(socket); 
      if(len) 
        { 
         int rsp_len; 
         //--- various reading commands depending on whether the connection is secure or not 
         if(ExtTLS) 
            rsp_len=SocketTlsRead(socket,rsp,len); 
         else 
            rsp_len=SocketRead(socket,rsp,len,timeout); 
         //--- analyze the response 
         if(rsp_len>0) 
           { 
            result+=CharArrayToString(rsp,0,rsp_len); 
            //--- print only the response header 
            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); 
              } 
           } 
        } 
     } 
   while(GetTickCount()<timeout_check && !IsStopped()); 
   return(false); 
  } 
//+------------------------------------------------------------------+ 
//| Script program start function                                    | 
//+------------------------------------------------------------------+ 
void OnStart() 
  { 
      Print("start socket!");
   int socket=SocketCreate(); 
   Print(socket);
//--- check the handle 
   if(socket!=INVALID_HANDLE) 
     { 
      //--- connect if all is well 
      if(SocketConnect(socket,Address,Port,1000)) 
        { 
         Print("Established connection to ",Address,":",Port); 

         string   subject,issuer,serial,thumbprint; 
         datetime expiration; 
         //--- if connection is secured by the certificate, display its data 
         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; 
           } 
         //--- send GET request to the server 
         if(HTTPSend(socket,"GET / HTTP/1.1\r\nHost: www.mql5.com\r\n\r\n")) 
           { 
            Print("GET request sent"); 
            //--- read the response 
            if(!HTTPRecv(socket,1000)) 
               Print("Failed to get a response, error ",GetLastError()); 
           } 
         else 
            Print("Failed to send GET request, error ",GetLastError()); 
        } 
      else 
        { 
         Print("Connection to ",Address,":",Port," failed, error ",GetLastError()); 
        } 
      //--- close a socket after using 
      SocketClose(socket); 
     } 
   else 
      Print("Failed to create a socket, error ",GetLastError()); 
  } 

0 个答案:

没有答案