首页 > 解决方案 > 将消息从 PHP 脚本发送到没有 ZMQ 或任何 PECL 包的 PHP 棘轮 websocket 服务器

问题描述

语境

我正在使用 RatchetPHP 让我的 HTML 客户端与自己同步。

websocket-server.php

我使用 运行这个文件php websocket-server.php,它无限循环以处理 websocket 连接和消息。

<?php

require __DIR__ . "/../vendor/autoload.php";

use Me\Server;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Server()
        )
    ),
    8000
);

$server->run();

客户端.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
    </head>
    <body>
        <script>
            var conn = new WebSocket("ws://127.0.0.1:8000");

            conn.onopen = function(e) {
                console.log("Connection established!");

                setTimeout(function() {
                    conn.send("coucou");
                }, 5000);
            };

            conn.onmessage = function(e) {
                console.log(e.data);
            };
        </script>
    </body>
</html>

我\Server.php

这是处理事件(消息、连接)的服务器。

namespace Me;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use SplObjectStorage;

class Server implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }
}

试图

我还需要我的后端将消息发送到套接字服务器,该服务器将自己向所有连接的客户端发送消息。这是一个 Laravel 后端,例如,它将向客户端发送一条消息,通知有新的用户记录可用并且他们应该重新加载他们的网页。这是我的尝试:

发送.php

$address="127.0.0.1";
$port="8000";
$msg="new user available";

$sock=socket_create(AF_INET,SOCK_STREAM,0) or die("Cannot create a socket");

socket_connect($sock,$address,$port) or die("Could not connect to the socket");
$result = socket_write($sock,$msg);

socket_close($sock);

我注意到的是 Ratchet 正在解析 HTTP 消息,所以如果我理解正确,我需要发送 HTTP 消息而不是普通消息(我确认了,因为如果我vendor/cboden/ratchet/src/Ratchet/Http/HttpServer.php在开始时在文件中解析原始消息之前打印原始消息在方法onMessage中,我可以看到我的消息,但是检查if (true !== $from->httpHeadersReceived) {没有通过,因为我正在发送原始文本)。

问题

如何在没有任何依赖项(如 ReactZMQ 和一些 PECL 包)的情况下向 Web 套接字服务器发送 HTTP 消息?

标签: phpwebsocketratchet

解决方案


推荐阅读