react-websocket/README.md

1.6 KiB

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);