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

查看:4047
本文介绍了使用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"."\r\n".
               "Upgrade: WebSocket"."\r\n".
               "Connection: Upgrade"."\r\n".
               "Origin: $local"."\r\n".
               "Host: $host"."\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客户端库(也许

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"."\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";

我的服务器正在使用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天全站免登陆