dongqing483174 2016-02-01 17:41
浏览 340

核心php中的websocket客户端

I am trying to send data to PHP websocket server, although it sends the data but the data received is a garbage values. How can fix this to get correct values posted to websocket php server?

Below is my websocket php client script

<?php
$host = 'example.com:9000/server.php';  //where is the websocket server
$port = 9000; //ssl
$local = "http://localhost/";  //url where this script run
$data = json_encode(array("server_msg"=> "1","device_id"=> "DDD-123455678"));  //data to be send

$head = "GET / HTTP/1.1"."
".
    "Host: $host"."
".
    "Upgrade: websocket"."
".
    "Connection: Upgrade"."
".
    "Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."
".
    "Sec-WebSocket-Version: 13"."
".
    "Content-Length: ".strlen($data)."
"."
";
////WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, "\x00$data\xff" ) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000);  //receives the data included in the websocket package "\x00DATA\xff"
$retdata = trim($wsdata,"\x00\xff"); //extracts data
////WebSocket handshake
fclose($sock);

echo $retdata;
?>

Thanks

Hi,

I have already tried it and it gives me error as below:

Fatal error: Uncaught exception 'WebSocket\ConnectionException' with message 'Connection to 'ws://************/server.php' in /var/www/webclientphp/vendor/textalk/websocket/lib/Client.php on line 149

WebSocket\ConnectionException: Connection to 'ws://************/server.php' failed: Server sent invalid upgrade response: HTTP/1.1 101 Web Socket Protocol Handshake Upgrade: websocket Connection: Upgrade WebSocket-Origin: ************ WebSocket-Location: ws://************:9000/demo/shout.php Sec-WebSocket-Accept:Kfh9QIsMVZcl6xEPYxPHzW8SZ8w= in /var/www/webclientphp/vendor/textalk/websocket/lib/Client.php on line 149

Please help

  • 写回答

1条回答 默认 最新

  • dsa89029 2016-02-01 19:09
    关注

    Your data needs to be encoded to match the Websocket protocol (frames, headers, encryption etc).

    The server will be expecting websocket frames, and will try to decode them as per the protocol, so you can't just send raw data. It will also send data to you in this format.

    The easiest way is to use a library, like this one

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器