問題描述
我正在嘗試在 Symfony2 中實現(xiàn) websockets,
I'm trying to implement websockets in Symfony2,
我發(fā)現(xiàn)這個 http://socketo.me/ 看起來不錯.
I found this http://socketo.me/ which seems pretty good.
我在 Symfony 中嘗試了它并且它有效,這只是使用 telnet 的一個簡單調(diào)用.但我不知道如何將其集成到 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.
我想我必須創(chuàng)建一個服務(wù),但我真的不知道哪種服務(wù)以及如何從客戶端調(diào)用它
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
感謝您的幫助.
推薦答案
首先你應(yīng)該創(chuàng)建一個服務(wù).如果您想注入實體管理器和其他依賴項,請在此處進行.
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: MyAppMyBundleChat
arguments:
- @doctrine.orm.default_entity_manager
在 src/MyApp/MyBundle/Chat.php 中:
And in src/MyApp/MyBundle/Chat.php:
class Chat implements MessageComponentInterface {
/**
* @var DoctrineORMEntityManager
*/
protected $em;
/**
* Constructor
*
* @param DoctrineORMEntityManager $em
*/
public function __construct($em)
{
$this->em = $em;
}
// onOpen, onMessage, onClose, onError ...
接下來,執(zhí)行控制臺命令來運行服務(wù)器.
Next, make a console command to run the server.
在 src/MyApp/MyBundle/Command/ServerCommand.php 中
In src/MyApp/MyBundle/Command/ServerCommand.php
use SymfonyBundleFrameworkBundleCommandContainerAwareCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
use RatchetServerIoServer;
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();
}
}
現(xiàn)在您有一個帶有依賴注入的 Chat 類,您可以將服務(wù)器作為控制臺命令運行.希望這會有所幫助!
Now you have a Chat class with dependency injections, and you can run the server as a console command. Hope this helps!
這篇關(guān)于如何在 Symfony2 中正確使用 webSockets的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!