如何在Symfony2中正确使用webSockets

Ajo*_*uve 30 php websocket symfony

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

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

我尝试使用Symfony它可以工作,这只是一个使用telnet的简单调用.但我不知道如何在Symfony中集成它.

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

谢谢你的帮助.

mat*_*exx 34

首先,您应该创建一个服务.如果要注入实体管理器和其他依赖项,请在那里执行.

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

services:
    chat:
        class: MyApp\MyBundle\Chat
        arguments: 
            - @doctrine.orm.default_entity_manager
Run Code Online (Sandbox Code Playgroud)

在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 ...
Run Code Online (Sandbox Code Playgroud)

接下来,创建一个控制台命令来运行服务器.

在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 有趣的是,使用带有棘轮服务器的学说将大部分时间导致"MySQL服务器已经消失"的错误.实际上,默认情况下,MySQL服务器将在8小时后关闭连接并且Doctrine不会自动重新连接到服务器,您必须手动处理它(请参阅http://stackoverflow.com/a/26791224/738091). (3认同)
  • 我不知道无法在您的托管服务上使用端口.听起来像你需要与提供商谈论的事情!您可以查看此答案http://stackoverflow.com/questions/17696344/starting-a-websockets-server-in-php-on-shared-hosting/17705521#17705521作为如何将服务器作为一个例子运行的示例守护进程使用PHP.但是如果你使用的是symfony,我会使用Process组件而不是popen和passthru.如果你想问这个问题,我可以告诉你我将使用的代码. (2认同)