title: PHP stream websockets
body: <p>Im kinda new with the sockets stuff and Im trying to make a server on PHP to support websockets calls from my javascript currently my code looks like this</p>
  
  <pre><code>&lt;?php
  
  class Websocket
  {
      private $server;
  
      private $sockets = [];
  
      public function create($host)
      {
          $this-&gt;server = stream_socket_server('tcp://localhost:8080', $errno, $errmsg);
          stream_set_blocking($this-&gt;server, 0);
      }
  
      public function run()
      {
          while(true)
          {
              $client = stream_socket_accept($this-&gt;server);
  
              if($client)
              {
                  $data = stream_socket_recvfrom($client, 2048);
  
                  if($data)
                  {
                      echo 'Client connected'.PHP_EOL;
                                          echo $data;
                      $response = $this-&gt;handshake($data);
  
                      stream_socket_sendto($client, $response);
                  }
              }
          }
      }
  
      private function handshake($data)
      {
          $data = explode(PHP_EOL, $data);
  
          foreach($data as $header)
          {
              $current_header = explode(':', $header);
  
              if($current_header[0] == 'Sec-WebSocket-Key')
              {
                  $accept = base64_encode(sha1(trim($current_header[1]).'258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
                  $response = 'HTTP/1.1 101 Switching Protocols'.PHP_EOL.'Upgrade: websocket'.PHP_EOL.'Connection: Upgrade'.PHP_EOL.'Sec-WebSocket-Accept:'.$accept.PHP_EOL.PHP_EOL;
  
                  return $response;
              }
          }
      }
  }
  </code></pre>
  
  <p>And my javascript is just a simple</p>
  
  <pre><code>var socket = new WebSocket('ws://localhost:8080');
  
  socket.onopen = function(event) 
  {
      console.log('connected');
      socket.send('hello');
  }
  </code></pre>
  
  <p>Currently the message connected appears on my chrome console but after that when the hello message is supposed to be sent I get this error</p>
  
  <p>"connection to: xxx was interrupted while the page was loading"</p>
  
  <p>So my question is after I have successfully send the handshake to the client how do I process messages? I know my code is always sending the handshake to new connections but on my server I will only see the first message beeing echoed (the http request) and not the "hello" one</p>