核心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个回答



您的数据需要编码以匹配 Websocket协议(帧,标题,加密等)。</ p>

服务器将期待websocket帧,并将根据协议尝试解码它们 ,所以你不能只发送原始数据。 它还将以这种格式向您发送数据。</ p>

最简单的方法是使用库,例如​​这一个 </ p>
</ div>

展开原文

原文

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

dousi6192
dousi6192 这听起来像服务器与客户端不兼容,可能使用过时的协议。 什么是服务器? 你有任何代码或控制权吗?
4 年多之前 回复
dongshi1148
dongshi1148 嗨,我已经尝试过了,它给了我错误。 有关错误详细信息,请参阅实际编辑的问题。
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问