首页 > 解决方案 > 制作一个多线程 websocket

问题描述

我使用棘轮和 php 制作了一个 Websocket 服务器,它工作正常,但问题是它不是多线程的,当多个客户端同时向服务器发送消息时,这会使服务器重播延迟。我想知道是否有任何方法可以使其成为多线程,以便每个连接都在它自己的线程上运行,或者如果它不是正确的方法,请给我一个更好的方法谢谢!

Chat.php 代码:

<?php
    namespace MyApp;
    use Ratchet\MessageComponentInterface;
    use Ratchet\ConnectionInterface;

    require 'vendor/autoload.php';

    require(dirname(dirname(__FILE__)).'/inc/class/class-app_api.php');

    class Chat implements MessageComponentInterface {
        protected $clients;
        public function __construct() {
            $this->clients = new \SplObjectStorage;
            echo 'server Started!';
        }

        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');
                $obj = new \app_api($from, $msg);
                $res = $obj->handleRequest();

                if (is_array($res)) {
                    foreach ($this->clients as $client) {
                        if ($from != $client) {
                            // The sender is not the receiver, send to each client connected
                            $client->send($res['data']);
                        }
                    }
                }else {
                    $from->send($res);
                }
        }

        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";
            $obj = new \venicehost_app_api($from);
            $conn->send($obj->setError('An error has occurred:' . $e->getMessage()));
            //$conn->close();
        }
    }
?>

Server.php 代码:

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;

require_once("Chat.php");
    //require dirname(__DIR__) . '/vendor/autoload.php';

    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Chat()
            )
        ),
        port,
        ip address
    );

    $server->run();
?>

标签: phpwebsocketratchetphpwebsocket

解决方案


推荐阅读