title: Is this the correct way to connect to a TCP port using PHP?
body: <p>A service is listening to port 1234 on 1xx.xxx.xx.xx
  I'm using php <code>fsockopen()</code> to establish a tcp connection with the service! I've to send incoming data to the service and save the reply I got from the service in a file.
  First time when I send data, the connection is established. The second time the code again tries to open the port and this time the service says, SP tries to connect. connection refused. An active SP connection exists. SP closed.</p>
  
  <p>How do I overcome this problem?</p>
  
  <pre><code>#!/usr/local/php5/bin/php-cgi
  &lt;?php 
  //The Client
  error_reporting(E_ALL);
  $CONTENT = $_GET["DATA"]."";
  echo urldecode($CONTENT);
  $Handle = fopen("/xxx/xxx/xxx.txt", "a");
  fwrite($Handle, $CONTENT);
  fclose($Handle);
  
  //$address = "1xx.xxx.xx.xx";
  //$port = 1234;
  
  /* Create a TCP/IP socket. */
  $fp = fsockopen("tcp://1xx.xxx.xx.xx",1234 , $errno, $errdesc); 
  if ( ! $fp ) {
    die ( "Couldn't connect to 1xx.xxx.xx.xx :\nError: $errno\nDesc: $errdesc\n" );
  }
  fputs ( $fp, $CONTENT );
  while ( ! feof( $fp ) ) {
    $output = fgets( $fp, 2048 );
  }
  fclose( $fp );
  $Handle1 = fopen("/xxx/xxx/yyy.txt", "a");
  fwrite($Handle1, $output);
  fclose($Handle1);
  
  ?&gt;
  </code></pre>