A simple class to connect to a websocket service. It handles negotiation with the socket server and handles the hybi10 frame encoding.
composer require dsentker/websocket-client
(WIP)
$client = new WebsocketClient('localhost', 8080);
$client->init(); // Init the Websocket Upgrade Request
$client->write('Hello World!'); // sends a message to websocket server
$content = $client->read(); // Read from websocket
On connection errors, an WebsocketClient\Exception\WebsocketException is thrown. If you want to mute this exceptions (e.g. with an unreliable websocket server or for log purposes) you can pass an ExceptionHandler
handler as third argument of the constructor:
$exceptionHandler = new ThrowHandler(); // Throws exceptions, as default
$exceptionHandler = new SilentHandler(); // Flushes exceptions down the toilet
$exceptionHandler = new LogHandler($yourLogger); // Log exceptions. Use any PSR-3-compatible logger instance here.
$client = new WebsocketClient('localhost', 8080, $exceptionHandler);
$client->init();
$client->write('Hello World!');
For an simple Websocket Server example, please visit Websocket Example by EcoParts (or implement the Server Library of your choice 😉 )
I have not found a working implementation for a websocket client in PHP. Many solutions were too complicated, required the installation of additional libraries or did not work at all. I came across PHP-websockets from paragi. This function set worked perfectly, but was not technically up to date. I have rewritten it for PHP 7.1 with an object-oriented approach and a composer repository.
- PHP >= 7.1.x
- An existing websocket server (e.g. ws or something else )
- Composer is recommended
Bugs and feature request are tracked on GitHub.
TBD (i know how important it is. I am looking forward to your help.)