【问题标题】:websocket client in core php核心php中的websocket客户端
【发布时间】:2016-05-10 06:43:48
【问题描述】:

我正在尝试向 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;
?>

谢谢

你好,

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

致命错误:在 /var/www/webclientphp/vendor/ 中未捕获异常 'WebSocket\ConnectionException' 并带有消息 'Connection to 'ws://************/server.php' textalk/websocket/lib/Client.php 在第 149 行

WebSocket\ConnectionException: Connection to 'ws://************/server.php' failed: Server sent invalid upgrade response: HTTP/1.1 101 Web Socket Protocol Handshake Upgrade: websocket连接:升级 WebSocket-Origin: ************ WebSocket-Location: ws://************:9000/demo/shout.php Sec-WebSocket -Accept:Kfh9QIsMVZcl6xEPYxPHzW8SZ8w= 在 /var/www/webclientphp/vendor/textalk/websocket/lib/Client.php 第 149 行

请帮忙

【问题讨论】:

    标签: php websocket


    【解决方案1】:

    您的数据需要进行编码以匹配Websocket protocol(帧、标头、加密等)。

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

    最简单的方法是使用库,例如​​this one

    【讨论】:

    • 嗨,我已经尝试过了,但它给了我错误。有关错误详情,请参阅实际编辑的问题。
    • 这听起来像是服务器与客户端不兼容,可能使用了过时的协议。服务器是什么?你有任何代码或控制它吗?
    猜你喜欢
    • 2011-11-01
    • 2021-09-14
    • 2018-04-07
    • 2018-02-28
    • 2016-10-10
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多