how to use properly webSockets in Symfony2

前端 未结 1 1685
北荒
北荒 2020-12-22 23:55

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

相关标签:
1条回答
  • 2020-12-23 00:47

    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!

    0 讨论(0)
提交回复
热议问题