>我正在尝试将数据发送到PHPwebsocket服务器,虽然它发送数据但接收的数据是垃圾值。如何解决此问题以将正确的值发布到 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"."rn".
"Host: $host"."rn".
"Upgrade: websocket"."rn".
"Connection: Upgrade"."rn".
"Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."rn".
"Sec-WebSocket-Version: 13"."rn".
"Content-Length: ".strlen($data)."rn"."rn";
////WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, "x00$dataxff" ) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000); //receives the data included in the websocket package "x00DATAxff"
$retdata = trim($wsdata,"x00xff"); //extracts data
////WebSocket handshake
fclose($sock);
echo $retdata;
?>
谢谢
你好
我已经尝试过了,它给了我如下错误:
致命错误:未捕获的异常"WebSocket\ConnectionException",在第 149 行的/var/www/webclientphp/vendor/textalk/websocket/lib/Client.php 中带有消息"连接到 'ws://******/server.php
WebSocket\ConnectionException: 连接到 'ws://**********/server.php' 失败: 服务器发送了无效的升级响应: HTTP/1.1 101 Web 套接字协议握手升级: websocket 连接: 升级 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
请帮忙
您的数据需要编码以匹配 Websocket 协议(帧、标头、加密等(。
服务器将期待 websocket 帧,并尝试根据协议对它们进行解码,因此您不能只发送原始数据。它还会以这种格式向您发送数据。
最简单的方法是使用库,就像这个