-2

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

Khalil
  • 119
  • 1
  • 14
  • I do not believe you couldn't find any documentation on how to use sockets and write if-else conditions and while cycles in C#. – Sejanus Sep 21 '16 at 11:10
  • yes I was too specific to MT4 and found a couple of example where they mentioned socket for "fsockopen". to save the time I have to post this question anyway. also I explicitly mentioned these (fsockopen-fputs-feof-fgets) – Khalil Sep 21 '16 at 11:56

1 Answers1

1

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;
    }
manda
  • 228
  • 1
  • 10
  • Yes it compiled and and run but the loop is infinite. And the received data characters are not recognized. Thanks great help nonetheless :). – Khalil Sep 21 '16 at 11:39