SessionProvider

Purpose of this Component

The SessionProvider will attach a Symfony2 Session object to each incoming Connection object that will give you read-only access to the session data from your web site. The SessionProvider will not work with any of the Native* session handlers. It is suggested you use choose one of the following Symfony Custom Save Handlers:

  • MemcacheSessionHandler
  • MemcachedSessionHandler
  • PdoSessionHandler
  • (in development) RedisSessionHandler

In order to access your session data in Ratchet, you must also use the same Symfony Session Handler on your web site. Below is a network diagram of how the various connections interact to access data:

Session Network Architecture

Important: Sessions through WebSockets work as they do through a traditional web server; a cookie is set and transmitted in each request header. This means that your web site and your WebSocket server both must have access to the cookie.
In order for session data to be shared between your web site and your WebSocket server they must be on the same domain. You can achieve this by either hosting them on the same domain and different ports, such as mydomain.com:80 (for web site) and mydomain.com:8080 (for WebSockets). If you choose to host the WebSocket server on a sub-domain (websocket.mydomain.com:80) make sure to have your web site's php.ini file configured like this:

session.cookie_domain = ".mydomain.com"

Events triggered by this Component

As found in the API Docs: Triggered events are propagated through a MessageComponentInterface object passed to the __construct.

  • onOpen (ConnectionInterface $conn, RequestInterface $request) - A new client connection has been opened
  • onClose (ConnectionInterface $conn) - A client connection is about to, or has closed
  • onError (ConnectionInterface $from, Exception $error) - An error has occurred with a Connection

Configuration methods

None.

Functions callable on Connections

  • send (string $message) - Send a message (string) to the client
  • close - Gracefully close the connection to the client

Parameters added to each Connection

(Symfony\Component\HttpFoundation\Session $Session) - A Symfony2 Session object. See the API docs or Symfony Documentation on working with the Session object. Also, please do not try and write to the session

Wraps other components nicely

Wrapped by other components nicely

Usage

<?php
// Your shell script
use Ratchet\Session\SessionProvider;
use Symfony\Component\HttpFoundation\Session\Storage\Handler;
use Ratchet\App;

    $memcache = new Memcache;
    $memcache->connect('localhost', 11211);

    $session = new SessionProvider(
        new MyApp
      , new Handler\MemcacheSessionHandler($memcache)
    );

    $server = new App('localhost');
    $server->route('/sessDemo', $session);
    $server->run();
<?php
    // Inside your MyApp class
    public function onOpen($conn) {
        $conn->send('Hello ' . $conn->Session->get('name'));
    }