I am newbie to Ratchet and Symfony both. I am trying to get familiar with them. I have used alternative to sessions which is quite weird but works. Here's it:
In JS (a native PHP session)
name = "<?php echo $_SESSION['name']; ?>";
msg = elem.value;
socket.send(name+"|"+msg);
The sent argument is then explode
with delimiter |
. It creates two strings. One is the name and other is msg which is then sent to all connections except the sender.
list($name, $message) = explode("|", $msg);
How can I use Symfony Session which saves nickname when user enters it and it will be accessible by my Chat class in MyApp namespace?
I have API docs but there is no simple example for using session. API Documentation
.
/www
|
|___/src
| |
| |____/MyApp/
| |
| |___Chat.php // The Chat Class
|
|___/bin
| |
| |___chat-server.php
|
|___/vendor
|
|___/chat.php // <-- Chat Room, sending and receiving here
|
|___/index.php // <-- Ask for nickname here
|
|___/composer.phar
|
|___/composer.lock
|
|___/main.js // <-- Index HTML javascript
|
|___/socket.js // <-- Websocket handler for char.php
|
|___/main.css // <-- All style
A controller can set the nickname to in the session:
/**
* @Route("/hello/{nickname}")
*/
public function indexAction($nickname)
{
$session = $this->getRequest()->getSession();
$session->set('nickname', $nickname);
}
To retrieve the nickname in your Chat app,
public function onOpen(ConnectionInterface $conn)
{
$nickname = $conn->Session->get('nickname');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.