Implementing a WebSocket server
To implement a WebSocket server, we'll use a library called cboden/ratchet
:
$ composer require cboden/ratchet
A WebSocket server is represented by a class implementing the MessageComponentInterface
interface with four methods onOpen()
, onClose()
, onError()
, and onMessage()
. How this class behaves on each of the events is up to the developer. Usually in chat applications, we want to keep all active connections in an array of clients and read messages, with onMessage()
to resend them to all clients.
We'll first implement only the required methods and then add some custom ones as well:
// ChatServer.php use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class ChatServer implements MessageComponentInterface { private $connections; private $history = []; private $subject; public function __construct() { $this->subject = new Subject(); } public...