title: Read data from socket, send response and close
body: <p>I am working on a c# and php project where the PHP script opens a socket to a c# program and the c# program will read the data and then send a response back. </p>
  
  <p>In the PHP script I have the following:</p>
  
  <pre><code>echo "Opening Client";
  
  $fp = fsockopen("127.0.0.1", 12345, $errno, $errstr, 30);
  
  if (!$fp)
  {
      echo "Error: $errstr ($errno)&lt;br /&gt;";
  }
  else
  {
      $out = "GET / HTTP/1.1\r\n";
      $out .= "Host: 127.0.0.1\r\n";
      $out .= "Connection: Close\r\n\r\n";
      fwrite($fp, $out);
      while (!feof($fp))
      {
          echo fgets($fp, 128);
      }
      fclose($fp);
  }
  </code></pre>
  
  <p>In the C# project I have the following:</p>
  
  <pre><code>public void startListen()
          {
              int port = 12345;
              IPAddress serverAddress = IPAddress.Parse("127.0.0.1");
              TcpListener listener = new TcpListener(serverAddress, 12345);
              listener.Start();
  
              TcpClient client = listener.AcceptTcpClient();
  
              NetworkStream stream = client.GetStream();
              byte[] data = new byte[client.ReceiveBufferSize];
              int bytesRead = stream.Read(data, 0, Convert.ToInt32(client.ReceiveBufferSize));
              string request = Encoding.ASCII.GetString(data, 0, bytesRead);
              Console.WriteLine(request);
  
              Console.ReadLine();
  </code></pre>
  
  <p>The PHP script seems to stay waiting and doesn't finish, I'm guessing its being its because the socket on the c# app to send a response back but I have no idea how to do this. Another problem, in the C# I need to have <code>Console.ReadLine()</code> otherwise the c# program will exit but the PHP Script does then finish as expected.</p>
  
  <p>Basically, what I want to know is this the best way to read the data that is sent on the socket, what is the best way to keep the program running so it keep on listening on the socket and how I send back a reply so that the php script can finish.</p>
  
  <p>Thanks for any help you can provide.</p>