使用PHP连接到棘轮Websocket服务器
作者:互联网
我在后端运行Ratchet WebSocketServer,一切正常.
<?php
require '../vendor/autoload.php';
use Ratchet\WebSocket\WsServer;
use Ratchet\Http\HttpServer;
$wsServer = new WsServer(new Chat());
$wsServer->disableVersion(0);
$server = \Ratchet\Server\IoServer::factory(
new HttpServer(
$wsServer
),
8080
);
$server->run();
但是我想使用简单的php脚本连接到websocket,以将消息发送到服务器.
$host = 'ws://localhost'; //where is the websocket server
$port = 8080;
$local = "http://example.com"; //url where this script run
$data = "first message"; //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:$port"."\r\n".
"Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."\r\n".
"Content-Length: ".strlen($data)."\r\n"."\r\n";
//WebSocket handshake
$sock = fsockopen($host, $port);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
echo $headers;
fwrite($sock, $data) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000);
fclose($sock);
但是我收到的错误是.
error:32744:Unable to find the socket transport "ws" - did you forget to enable it when you configured PHP?
然后,当我更改主机并且不使用ws://时,它说.
error:111:Connection refused
有谁知道如何将数据从纯PHP文件发送到正在运行的Ratchet WebSocket服务器?
解决方法:
我已经与Ratchet一起尝试了这个项目,它可以完美地用作PHP客户端:
https://github.com/Textalk/websocket-php
安装方式:
作曲家需要textalk / websocket 1.0.*
还有一个用法示例:
<?php
require('vendor/autoload.php');
use WebSocket\Client;
$client = new Client("ws://127.0.0.1:1234");
$client->send("Hello from PHP");
echo $client->receive() . "\n"; // Should output 'Hello from PHP'
我进行了测试,如果您使用wss://(用于远程websocket),则该方法也可用于SSL.
标签:ratchet,php-socket,sockets,websocket,php 来源: https://codeday.me/bug/20191026/1939690.html