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 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组