How To Implement Wildcard Routes With Ratchet WebSocket server
Ratchet uses Symfony router component and has good documentation for its Routing. However, getting it to work with Ratchet 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
anotherThing. By doing so we indicate that these are placeholders for our wildcard routes and not literal strings.
We have passed the `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
Let’s create our class “MyApp”
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
getQuery() call returns us our values for the wildcard path placeholders
anotherThing in query-string format i.e
We parse it using parse_str function and store it in
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
Bonus Tip: Solve 404 not found on production
If you use the exact same configuration as above, things will work well on localhost. However, you will get a 404 error for your WebSocket connection even on valid routes.
To fix that, change
$server = new Ratchet\App("localhost",12345, '0.0.0.0');
$server = new Ratchet\App("YOUR_PRODUCTION_HOST",12345, '0.0.0.0');
YOUR_PRODUCTION_HOST with the host on which your WebSocket is running, e.g: example.com.