Native WebSocket library for ReactPHP
Go to file
2024-02-21 12:57:10 +01:00
doc Added documentation for connection groups 2024-02-21 12:57:10 +01:00
examples Initial commit 2024-02-21 03:03:08 +01:00
src Cleanup send code in WebSocketConnection 2024-02-21 03:17:11 +01:00
.gitignore Initial commit 2024-02-21 03:03:08 +01:00
composer.json Initial commit 2024-02-21 03:03:08 +01:00
LICENSE Initial commit 2024-02-21 03:03:08 +01:00
README.md Initial commit 2024-02-21 03:03:08 +01:00

ReactPHP WebSockets

Installing

Install using composer:

$ composer require noccylabs/react-websocket

Why not Ratchet?

Ratchet is great! I've used Ratchet in the past, and it is a fantastic piece of code. It is however more application-centered, which means it doesn't do events and all that beautiful magic we've come to love ReactPHP for.

TL;DR - If you need to build an application with neatly wrapped classes without caring to much about the internals, go with Ratchet. If you want to work with websockets in the same way you work with sockets in ReactPHP, go with this library.

Example

// This is the middleware that will intercept WebSocket handshakes
$websocket = new NoccyLabs\React\WebSocket\WebSocketMiddleware();

// Connect event handler, receives a WebSocketInterface.
// Ratchet handles security for you, this library does not. You should
// check everything important in the connect handdler and reject anything
// that does not smell right. Here we just echo everything.
$websocket->on('connect', function (NoccyLabs\React\WebSocket\WebSocketInterface $connection) {
    $websocket->on('text', function ($text) use ($websocket) {
        $websocket->write($text);
    });
});

// The HTTP router that will handle other requests
$router = function (Psr\Http\Message\ServerRequestInterface $request) {
    return React\Http\Message\Response::plaintext("This is a websocket server");
};

// Create a HttpServer and insert the middleware
$http = new React\Http\HttpServer(
    $websocket,
    $router
);

// Create a socket and listen as you're used to
$socket = new React\Socket\SocketServer('0.0.0.0:8000');
$http->listen($socket);