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条回答

    报告相同问题?

    悬赏问题

    • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
    • ¥15 让node服务器有自动加载文件的功能
    • ¥15 jmeter脚本回放有的是对的有的是错的
    • ¥15 r语言蛋白组学相关问题
    • ¥15 Python时间序列如何拟合疏系数模型
    • ¥15 求学软件的前人们指明方向🥺
    • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
    • ¥20 双层网络上信息-疾病传播
    • ¥50 paddlepaddle pinn
    • ¥20 idea运行测试代码报错问题