title: tcp client connection in php
body: <p>I have a webservice which connects to a server and return result as xml or json. It is written in asp.net. I want to use the same in php.</p>
  
  <pre><code>using (TcpClient tcpClient = new TcpClient()) 
      { 
          tcpClient.Connect("1.1.1.1", port: 42011);
          string search = "search^10|5|2|1^gagl^55592a782ce899d2" + 
  System.Environment.NewLine; 
          using (NetworkStream ns = tcpClient.GetStream()) 
          { 
              byte[] bytes = ASCIIEncoding.ASCII.GetBytes(search); 
              ns.Write(bytes, 0, bytes.Length); 
              string result = ReadBuffer(ns); 
  
            // [.. consume result XML string ..] 
  
          } 
          tcpClient.Close(); 
      }
          }
  protected string ReadBuffer(NetworkStream ns) 
  { 
      byte[] lenghtBuffer = new byte[4]; 
      int bytesRead = 0; 
      while (bytesRead &lt; 4) 
          bytesRead += ns.Read(lenghtBuffer, bytesRead, 4 - bytesRead); 
      if (BitConverter.IsLittleEndian) 
          Array.Reverse(lenghtBuffer); 
      int responseLength = BitConverter.ToInt32(lenghtBuffer, 0); 
      byte[] buffer = new byte[responseLength]; 
      bytesRead = 0; 
      while (bytesRead &lt; responseLength) 
          bytesRead += ns.Read(buffer, bytesRead, responseLength - bytesRead); 
      string result = ASCIIEncoding.ASCII.GetString(buffer, 0, bytesRead); 
      return result; 
  } 
  </code></pre>
  
  <p>The above codes return values in .net. How to get the result in php using the same values.</p>