dongqiang4986 2019-02-26 19:38
浏览 130

WebSockets PHP - 如何从js接收消息

I try to create my first simple websocket on pure php without any frameworks. I have successfully sent message from php to multiple clients but now I want to send messages from js to php but I always fail. Can you tell me what I do wrong? This is my php code:

$clients=array();
$address='127.0.0.1';
$port=9988;
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
//socket_set_option($socket,SOL_SOCKET,SO_REUSEADDR,1);
socket_bind($socket,$address,$port);
socket_listen($socket);
socket_set_nonblock($socket);

while(true){
    sleep(1);
    $newc=socket_accept($socket);
    if($newc!==false){
        //echo "Client ".$newc." has connected<br />
";
        $clients[]=$newc;

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

";
        socket_write($clients[count($clients)-1],$headers,strlen($headers));
    }

    foreach($clients as $client){
        $content='Now: '.time();
        $response=chr(129).chr(strlen($content)).$content;
        socket_write($client,$response);

        /*@socket_recv($socket,$buf,8192,0);
        echo "Client ".$client." has sent \"".$buf."\"<br />
";*/
    }
}

and this is my js code:

<html>
<body>
    <div id="root"></div>
    <script>
        var host='ws://127.0.0.1:9988/socket.php';
        var socket=new WebSocket(host);
        socket.onmessage=function(e){
            document.getElementById('root').innerHTML=e.data;
        };
        setInreval(function(){
            websocket.send(JSON.stringify({data:Math.random()*(max-min)+min}));
        },500)
    </script>
</body>
</html>

As you see I try to send random number to php from js but I cant get it in php..

Any help appriciated! Thanks!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 stata安慰剂检验作图但是真实值不出现在图上
    • ¥15 c程序不知道为什么得不到结果
    • ¥40 复杂的限制性的商函数处理
    • ¥15 程序不包含适用于入口点的静态Main方法
    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题