Javascript websocket不会连接到php websocket

So I've been trying to get this whole connection between PHP socket server and Javascript websockets working, but I cant get them to connect. I have looked everywhere to figure out what I'm doing wrong. My guess is it's the protocol but I have no idea. Everything helps, comment if you have questions.

Client-Side Example

<script>

    var connection = new WebSocket('ws://127.0.0.1:4446');

    connection.onopen = function () {
        connection.send('Ping'); // Send the message 'Ping' to the server
    };

    // Log errors
    connection.onerror = function (error){
        console.log('WebSocket Error ' + error);
    };

    // Log messages from the server
    connection.onmessage = function (e) {
        console.log('Server: ' + e.data);
    };

</script>

Server-Side Example -PHP

<?php

    $conn = stream_socket_server('tcp://127.0.0.1:4446');
    while ($socket = stream_socket_accept($conn)) {
        $pkt = stream_socket_recvfrom($socket, 1500, 0, $peer);
        if (false === empty($pkt)) {
            stream_socket_sendto($socket, $pkt, 0, $peer);
        }
        fclose($socket);
        usleep(10000); //100ms delay
    }
    stream_socket_shutdown($conn, \STREAM_SHUT_RDWR);

?>

Console Log Error

VM4666:35 WebSocket connection to 'ws://127.0.0.1:4446/' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE

I understand that there are many questions on here similar but I cant seem to find a solution, I appreciate any help!

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐