Simple websocket in php

雨燕双飞 提交于 2020-07-22 11:06:38

问题


I want to implement a simple websocket in php with a simple response ( date / time response ). I tried this implementation but I ended up with some unknown error response.

HTML - Client

<html>
<body>
  <div id="root"></div>
  <script>
    var host = 'wss://myWebsite.com:8090/simple-ws/ws.php';
    var socket = new WebSocket(host);
    socket.onmessage = function(e) {
        document.getElementById('root').innerHTML = e.data;
    };

    socket.onerror = function(e) {
        console.warn('Error FE', e)
    };

  </script>
  </body>
</html>

PHP - Server

<?php

try {

    $address = 'https://myWebsite.com/';
    $port = 8090;

    // Create WebSocket.
    $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
    socket_bind($server, $address, $port);
    socket_listen($server);

    $client = socket_accept($server);
    // Send WebSocket handshake headers.
    $request = socket_read($client, 5000);
    preg_match('#Sec-WebSocket-Key: (.*)\r\n#', $request, $matches);
    $key = base64_encode(pack(
        'H*',
        sha1($matches[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
    ));
    $headers = "HTTP/1.1 101 Switching Protocols\r\n";
    $headers .= "Upgrade: websocket\r\n";
    $headers .= "Connection: Upgrade\r\n";
    $headers .= "Sec-WebSocket-Version: 13\r\n";
    $headers .= "Sec-WebSocket-Accept: $key\r\n\r\n";
    socket_write($client, $headers, strlen($headers));

    // Send messages into WebSocket in a loop.
    while (true) {
        sleep(1);
        $content = 'Now: ' . time();
        $response = chr(129) . chr(strlen($content)) . $content;
        socket_write($client, $response);
    }

} catch (Exception $e) {
    echo 'Error on ws'.$e;
}

?>

After 4-6 seconds I get response:

WebSocket connection to 'wss://myWebsite.com:8090/simple-ws/ws.php' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT

Error response from onerror callback:

{
  bubble: false,
  cancelBubble: false,
  cancelable: false,
  type: "error",
  target: WebSocket {url: "wss://myWebsite.com:8090/simple-ws/ws-php", readyState: 3}
}

来源:https://stackoverflow.com/questions/48344809/simple-websocket-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!