如何在 Symfony2 中正确使用 webSockets

2021-12-25 00:00:00 websocket php symfony

我正在尝试在 Symfony2 中实现 websockets,

I'm trying to implement websockets in Symfony2,

我发现这个 http://socketo.me/ 看起来不错.

I found this http://socketo.me/ which seems pretty good.

我在 Symfony 中尝试了它并且它有效,这只是使用 telnet 的一个简单调用.但我不知道如何将其集成到 Symfony 中.

I try it out of Symfony and it works, this was just a simple call using telnet. But I don't know how to integrate this in Symfony.

我想我必须创建一个服务,但我真的不知道哪种服务以及如何从客户端调用它

I think I have to create a service but I don't know realy which kind of service and how to call it from the client

感谢您的帮助.

推荐答案

首先你应该创建一个服务.如果您想注入实体管理器和其他依赖项,请在此处进行.

First you should create a service. If you want to inject your entity manager and other dependencies, do it there.

在 src/MyApp/MyBundle/Resources/config/services.yml 中:

In src/MyApp/MyBundle/Resources/config/services.yml:

services:
    chat:
        class: MyAppMyBundleChat
        arguments: 
            - @doctrine.orm.default_entity_manager

在 src/MyApp/MyBundle/Chat.php 中:

And in src/MyApp/MyBundle/Chat.php:

class Chat implements MessageComponentInterface {
    /**
     * @var DoctrineORMEntityManager
     */
    protected $em;
    /**
     * Constructor
     *
     * @param DoctrineORMEntityManager $em
     */
    public function __construct($em)
    {
        $this->em = $em;
    }
    // onOpen, onMessage, onClose, onError ...

接下来,执行控制台命令来运行服务器.

Next, make a console command to run the server.

在 src/MyApp/MyBundle/Command/ServerCommand.php 中

In src/MyApp/MyBundle/Command/ServerCommand.php

use SymfonyBundleFrameworkBundleCommandContainerAwareCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
use RatchetServerIoServer;

class ServerCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('chat:server')
            ->setDescription('Start the Chat server');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $chat = $this->getContainer()->get('chat');
        $server = IoServer::factory($chat, 8080);
        $server->run();
    }
}

现在您有一个带有依赖注入的 Chat 类,您可以将服务器作为控制台命令运行.希望这会有所帮助!

Now you have a Chat class with dependency injections, and you can run the server as a console command. Hope this helps!

相关文章