duanba7653 2017-04-25 03:19
浏览 117

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!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料