How to implement wildcard routes in Ratchet WebSocket server

Ratchet uses Symfony router component and has a good documentation for its Routing. However, getting it to work with Ractche WebSocket server might be a little tricky. Below is a complete guide that will put your search to an end if you are looking for an example of wildcard routes implementation in Ratchet WebSocket server.

Ratchet version used for this guide is: 0.4.1

Wildcard Routes in Ratchet

Let us create a file server.php, we will have the entire code in a single file for the sake of simplicity here. You can use this implementation as per your project structure.

Creating the route

We create a Ratchet WebSocket server with wildcard routes using the code below:

Notice that while calling the route method we place curly braces around something and anotherThing. By doing so we indicate that these are placeholders for our wildcard routes and not literal strings.

We have passed `MyApp` class as a controller for our server, We will create this class in the next step.

Retrieving the route values

We have assigned placeholders for our wildcard route and that was easy. How do we retrieve them in our WebSocket server events like onOpen, onMessage or onError ?

Let’s create our class “MyApp”

The methods onMessage,onClose and onError are left empty.

Have a look at onOpen method, the line $request = $conn->httpRequest; retrieves $request object form the connection.

Then we retrieve query strings from it by using $request->getUri()->getQuery()

The getQuery() call returns us our values for the wildcard path placeholders something and anotherThing in query-string format i.e something=x&anotherThing=y

We parse it using parse_str function and store it in $query_strings variable.

You can now access your WebSocket server using ws://your_server.com:12345/andy/hack4m where andy and hack4m are arbitrary values for your wildcard route placeholders.

Full code for server.php:

Bonus Tip: Solve 404 not found on production

If you use the exact same configuration as above, things will work good on localhost. However, you will get 404 error for your WebSocket connection even on valid routes.

To fix that, change

$server = new Ratchet\App("localhost",12345, '0.0.0.0');

to
 $server = new Ratchet\App("YOUR_PRODUCTION_HOST",12345, '0.0.0.0');
 Replace YOUR_PRODUCTION_HOST with the host on which your WebSocket is running, e.g: example.com.


Originally published at Hack4m.