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

时间:2016-07-20 09:24:14

标签: php sockets websocket ratchet php-socket

我在后端运行一个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服务器发送数据?

1 个答案:

答案 0 :(得分:4)

我和Ratchet一起尝试过这个项目,它作为一个PHP客户端非常有效:

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

安装时: composer require 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://(用于远程websockets),这也适用于SSL。