核心php中的websocket客户端

时间:2016-02-01 17:41:55

标签: 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 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 / webclientphp / vendor /中显示消息'连接到'ws://************/server.php'第149行的textalk / websocket / lib / Client.php

WebSocket \ ConnectionException:与'ws://************/server.php'的连接失败:服务器发送了无效的升级响应:HTTP / 1.1 101 Web套接字协议握手升级:websocket连接:升级WebSocket-Origin:************ WebSocket-Location:ws:// ************:9000 / demo / shout.php Sec-WebSocket - 接受:Kfh9QIsMVZcl6xEPYxPHzW8SZ8w =在第149行的/var/www/webclientphp/vendor/textalk/websocket/lib/Client.php

请帮忙

1 个答案:

答案 0 :(得分:1)

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

服务器将需要websocket框架,并将根据协议尝试解码它们,因此您无法发送原始数据。它还会以这种格式向您发送数据。

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