核心php中的websocket客户端

核心php中的websocket客户端,php,websocket,Php,Websocket,我试图将数据发送到PHP websocket服务器,虽然它发送数据,但接收到的数据是垃圾值。如何修复此问题以获得发布到websocket php服务器的正确值 下面是我的websocket php客户端脚本 <?php $host = 'example.com:9000/server.php'; //where is the websocket server $port = 9000; //ssl $local = "http://localhost/"; //url where th

我试图将数据发送到PHP websocket服务器,虽然它发送数据,但接收到的数据是垃圾值。如何修复此问题以获得发布到websocket php服务器的正确值

下面是我的websocket php客户端脚本

<?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"."\r\n".
    "Host: $host"."\r\n".
    "Upgrade: websocket"."\r\n".
    "Connection: Upgrade"."\r\n".
    "Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."\r\n".
    "Sec-WebSocket-Version: 13"."\r\n".
    "Content-Length: ".strlen($data)."\r\n"."\r\n";
////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;
?>

谢谢

我已经试过了,它给我的错误如下:

致命错误:未捕获异常“WebSocket\ConnectionException”,在/var/www/webclienthp/vendor/textalk/WebSocket/lib/Client.php的第149行显示消息“连接到”ws://******************/server.php“

WebSocket\ConnectionException:连接到'ws://***************/server.php'失败:服务器发送了无效的升级响应:HTTP/1.1 101 Web套接字协议握手升级:WebSocket连接:升级WebSocket源代码:*************WebSocket位置:ws://**************:9000/demo/shout.php Sec WebSocket接受:Kfh9QIsMVZcl6xEPYxPHzW8SZ8w=in/var/www/webclienthp/vendor/textalk/websocket/lib/Client.php,第149行


请帮助

您的数据需要编码以匹配(帧、标题、加密等)

服务器将期待websocket帧,并将尝试按照协议对其进行解码,因此您不能只发送原始数据。它还将以这种格式向您发送数据


最简单的方法是使用库,比如

Hi,我已经尝试过了,但它给了我错误。有关错误详细信息,请参阅实际编辑的问题。听起来服务器与客户端不兼容,可能使用了过时的协议。服务器是什么?你有任何代码或控制它吗?