예제 #1
0
 /**
  * Does the magic handshake to begin the connection
  *
  * @param string $buffer Buffer sent by the client
  * @return bool Was the handshake successful
  * @throws Exception If something goes wrong
  */
 public function performHandshake($buffer)
 {
     if ($this->state != self::STATE_CONNECTING) {
         throw new Exception('Unable to perform handshake, client is not in connecting state');
     }
     $this->headers = $headers = $this->parseRequestHeader($buffer);
     $key = $headers['Sec-WebSocket-Key'];
     $hash = base64_encode(sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
     $headers = array('HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', 'Sec-WebSocket-Accept: ' . $hash);
     $headers = implode("\r\n", $headers) . "\r\n\r\n";
     $left = strlen($headers);
     do {
         $sent = @socket_send($this->socket, $headers, $left, 0);
         if ($sent === false) {
             $error = $this->server->getLastError();
             throw new Exception('Sending handshake failed: : ' . $error->message . ' [' . $error->code . ']');
         }
         $left -= $sent;
         if ($sent > 0) {
             $headers = substr($headers, $sent);
         }
     } while ($left > 0);
     $this->state = self::STATE_OPEN;
 }