Search code examples
c#phpcode-conversionmt4

Convert PHP Code Block (fsockopen, fputs, feof, fgets) into C#


I need someone to convert this php code block into equivalent C#. We are working on MT4 to register user via asp.net web application. We have been given the php version of the site to post the user information. every things is setup accordingly. however the following code block need to be converted. I tried to search online solution but could not find any documentation thanks.

function MQ_Query($query)
{
$ret='error';
//---- open socket
$ptr=@fsockopen(T_MT4_HOST,T_MT4_PORT,$errno,$errstr,5); 
//---- check connection
 if($ptr)
 {
  //---- send request
  if(fputs($ptr,"W$query\nQUIT\n")!=FALSE)
    {
     //---- clear default answer
     $ret='';
     //---- receive answer
     while(!feof($ptr)) 
      {
       $line=fgets($ptr,128);
       if($line=="end\r\n") break; 
       $ret.= $line;
      } 
    }
  fclose($ptr);
  }
  //---- return answer
 return $ret;

 }

please


Solution

  • Here it is. The only thing I am not sure about is how to recognize EOF. You should try this snippet - it should throw exception if socket closes, or doesn't have anything to read. Otherwise, it will return after 2000 reads by 128 bytes. You can arrange this the way you like

        private static string T_MT4_HOST = "188.120.127.95";
        private static int T_MT4_PORT = 80;
    
        public static string MQ_Query(string query)
        {
            var i = 0;
            IPAddress[] IPs = Dns.GetHostAddresses(T_MT4_HOST);            
            var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    
            s.Connect(IPs, T_MT4_PORT);            
            s.Send(Encoding.ASCII.GetBytes(String.Format("W{0}\nQUIT\n", query));
            var received = new byte[128];
            string ret = "";
            while (i<100)
            {
    
                s.Receive(received);
                var r = Encoding.ASCII.GetString(received);
                if (r.StartsWith("end\r\n"))
                    break;
                ret += r;
                i++;
            }
    
            s.Close();
            return ret;
        }