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 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名