phpsocketswebsocketphp-socket

PHP Websocket failed: Error during WebSocket handshake: net::ERR_CONNECTION_CLOSED (anonymous)


i learning the websocket in PHP but i don't know why have this handshake error.

My client.html :

<html>
<body>
    <div id="root"></div>
    <script>
        var host = 'ws://127.0.0.1:8020/';
        var socket = new WebSocket(host);
        socket.onmessage = function(e) {
            console.log(e.data)
        };
    </script>
</body>
</html>

And server.php :

<?php

$address = "127.0.0.1";
$port = 8020;

$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,$address,$port) or die('bind error');
socket_listen($socket) or die('listen error');
$client = socket_accept($socket) or die('accept error');

$socketread = socket_read($client,5000) or die('Failed to read');

preg_match("#Sec-WebSocket-Key: (.*)\r\n#",$socketread,$match);
$key = base64_encode(sha1($match[1].'258EAFA5-E914-47DA-95CA-C5AB0DC85B11',true));

$header = "HTTP/1.1 101 Switching Protocols\r\n";
$header .= "Upgrade: websocket\r\n";
$header .= "Connection: Upgrade\r\n";
$header .= "Sec-WebSocket-Accept: $key\r\n";
$header .= "Sec-WebSocket-Version: 13\r\n";

var_dump($header);
socket_write($client,$header,strlen($header));


$msg = "connected";
socket_write($client,$msg,strlen($msg));
socket_close($socket);

However, I followed the Mozilla documentation on the handshake :/

Thank you for that.


Solution

  • However, I followed the Mozilla documentation on the handshake :/

    While this might be you assume based on your code that only the handshake at the beginning is needed and that you can just use a plain socket directly. But WebSockets actually have their own message structure and also payload masking which you need to implement too. See the actual standard for the details.