Creating a Ratchet Web Socket Server with Laravel

TL;DR: Check out the package.

I’ve been building an api for the past couple months and we’ve come to the point where the frontend needs to do some status checks. Status checks currently ping the crap out of the current api and are pretty darn slow.

The solution for us is a Socket based status check, the frontend connects, validates and performs checks as it sees fit.

There are many other reasons to use sockets in your web application, the most common example is a Chat server, but you can do almost anything with a Web Socket.

Ratchet?

“Ratchet is a loosely coupled PHP library providing developers with tools to create real time, bi-directionalapplications between clients and servers over WebSockets. This is not your Grandfather’s Internet.”

Basically in a few lines we get a full socket server with a lot of options, it’s really easy to get going.

Google around for Laravel Ratchet and you’ll land on this example. It’s pretty basic and is a great start for including Ratchet in Laravel but I wanted a bit more, a package, some options, an easy way to add my own server.

Introducing Laravel Ratchet

Laravel Ratchet is a simple package I made that allows you to create a Ratchet Socket Server with minimal effort. Simply create a custom MessageComponentInterface or one that extends mine and you’ll be up and running in no time.

Here is an example of a server we can telnet to that responds to us, everyone, then kicks us off:

<?php
namespace App;
use Ratchet\ConnectionInterface;
class RatchetServer extends \Askedio\LaravelRatchet\RatchetServer
{
public function onMessage(ConnectionInterface $conn, $input)
{
parent::onMessage($conn, $input);
$this->send($conn, 'Hello you.'.PHP_EOL);
$this->sendAll('Hello everyone.'.PHP_EOL);
$this->send($conn, 'Wait, I don\'t know you! Bye bye!'.PHP_EOL);
$this->abort($conn);
}
}

Read over the github page to learn how to configure it with your own class.

Conclusion

Ratchet is pretty cool. It was really easy to get setup and added to laravel. With this package I can focus on building the actions in the server instead of the server itself. If others find it useful and actually contribute that’d make it even better.