Home » Php » php – how to use properly webSockets in Symfony2

php – how to use properly webSockets in Symfony2

Posted by: admin April 23, 2020 Leave a comment


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.

How to&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:

        class: MyApp\MyBundle\Chat
            - @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()
            ->setDescription('Start the Chat server');

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

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