使用 PHP 客户端连接到 websocket [英] Connecting to websocket with PHP client

查看:99
本文介绍了使用 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-clienthttps://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);

完整的协议规范是:https://tools.ietf.org/rfc/rfc6455.txt

这篇关于使用 PHP 客户端连接到 websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆