title: php socket connection using localhost through Telnet
body: <p>I been trying to create socket and bind it to the localhost <code>127.0.0.1</code> and trying to connect to it using Microsoft's telnet service, but where ever I connect to the specified address and port I get the following error.</p>
  
  <blockquote>
    <p>PHP Warning:  socket_write(): unable to write to socket [0]: A request to sen
    d or receive data was disallowed because the socket is not connected and (when s
    ending on a datagram socket using a sendto call) no address was supplied.</p>
  </blockquote>
  
  <p>A similar error is returned by the socket_read, I dont understand telnet should just work right giving a socket_connect request to the localhost.</p>
  
  <p>Here's the code:</p>
  
  <pre><code>set_time_limit(0);
  $socket=null;
  $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
  if(socket_bind($socket,"127.0.0.1",58)){    
      if(!socket_listen($socket,0)){
          echo "Problem Listening to the socket";
      }do{
          $res=socket_accept($socket);
          $write="\n Hello the connection has been established";  
          if(!socket_write($socket,$write,strlen($write))){
              echo "Problem Reading the and writing to the socket";
              }                   
              do{
              if(!$clientmsg=socket_read($socket,2048,PHP_NORMAL_READ)){
                  echo "Error reading Client Msg";
                  break;
                      }
              $repsonse= "Thanks for you input";
              socket_write($socket,$response,strlen($response));
              if($nclientmsg=trim($clientmsg)){
                  continue;
              }
              if($clientmsg="close"){
                  socket_close($socket);
                  echo "The socket has been closed as promised Thanks";
                  break 3;
                  }
              }while(true);
              }while(true);
  }else{
      echo "Problem connecting to the socket.Unable to bind to the specified address";
  }
  </code></pre>
  
  <p>Thanks.</p>