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类,您可以将该服务器作为控制台命令运行.希望这可以帮助!