如何在Symfony2中正确使用webSockets [英] how to use properly webSockets in Symfony2

查看:96
本文介绍了如何在Symfony2中正确使用webSockets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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: MyApp\MyBundle\Chat
        arguments: 
            - @doctrine.orm.default_entity_manager

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

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

class Chat implements MessageComponentInterface {
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $em;
    /**
     * Constructor
     *
     * @param \Doctrine\ORM\EntityManager $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 Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Ratchet\Server\IoServer;

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!

这篇关于如何在Symfony2中正确使用webSockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆