使用PHP连接到棘轮websocket服务器



我正在后台运行Ratchet WebSocketServer,一切正常。

<?php
require '../vendor/autoload.php';
use RatchetWebSocketWsServer;
use RatchetHttpHttpServer;
$wsServer = new WsServer(new Chat());
$wsServer->disableVersion(0);
$server = RatchetServerIoServer::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"."rn".
    "Upgrade: WebSocket"."rn".
    "Connection: Upgrade"."rn".
    "Origin: $local"."rn".
    "Host: $host:$port"."rn".
    "Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."rn".
    "Content-Length: ".strlen($data)."rn"."rn";
//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文件将数据发送到正在运行的RatchetWebSocketServer吗?

我和Ratchet一起尝试过这个项目,它可以完美地作为PHP客户端:

https://github.com/Textalk/websocket-php

安装方式:composer require textalk/websocket 1.0.*

还有一个用法示例:

<?php
require('vendor/autoload.php');
use WebSocketClient;
$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。

相关内容

  • 没有找到相关文章

最新更新