使用 PHP 客户端连接到 websocket
我正在尝试将基于 PHP 的客户端连接到 websocket 服务器.
I'm trying to connect a PHP-based client to a websocket server.
这是我一直在使用的代码,它已在不同的论坛上广泛发布.但由于某种原因,我无法让它工作.
Here's the code I have been using which has been widely published on different forums. But for some reason I just cannot get it to work.
任何帮助将不胜感激.
$host = 'host'; //where is the websocket server
$port = 443; //ssl
$local = "http://www.example.com/"; //url where this script run
$data = '{"id": 2,"command": "server_info"}'; //data to be send
$head = "GET / HTTP/1.1"."
".
"Upgrade: WebSocket"."
".
"Connection: Upgrade"."
".
"Origin: $local"."
".
"Host: $host"."
".
"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$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 客户端库(也许 https://github.com/gabrielbull/php-websocket-client 或 https://github.com/Devristo/phpws/tree/master/src/Devristo/Phpws/Client ?)而不是自己动手,但我得到了它至少通过使用连接:
I would probably prefer to use an existing websocket client library (maybe https://github.com/gabrielbull/php-websocket-client or https://github.com/Devristo/phpws/tree/master/src/Devristo/Phpws/Client ?) rather than roll your own, but I got it to at least connect by using:
$head = "GET / HTTP/1.1"."
".
"Host: $host"."
".
"Upgrade: websocket"."
".
"Connection: Upgrade"."
".
"Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."
".
"Sec-WebSocket-Version: 13"."
".
"Content-Length: ".strlen($data)."
"."
";
我的服务器使用 TLS/SSL,所以我还需要:
My server is using TLS/SSL, so I also needed:
$sock = fsockopen('tls://'.$host, $port, $errno, $errstr, 2);