Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use properly webSockets in Symfony2

I'm trying to implement websockets in Symfony2,

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

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

Thanks for your help.

like image 669
Ajouve Avatar asked Jul 08 '13 14:07

Ajouve


1 Answers

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

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

services:
    chat:
        class: MyApp\MyBundle\Chat
        arguments: 
            - @doctrine.orm.default_entity_manager

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.

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();
    }
}

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

like image 185
mattexx Avatar answered Nov 12 '22 07:11

mattexx