react-websocket/README.md

85 lines
2.8 KiB
Markdown
Raw Normal View History

2024-02-21 02:03:08 +00:00
# ReactPHP WebSockets
## Installing
Install using composer:
```shell
$ 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.
2024-02-21 20:34:37 +00:00
## Server
The WebSocket handler is built as a HttpServer middleware. This makes sense as WebSocket as a protocol is running over HTTP. Connections are set up by the middleware and exposed via the `connect` event.
Data is written and read as with any DuplexStream, use the write() method to send data to the client, and listen for the text and binary events on the connection.
Note that the write() method sends text frames, if you want to send a binary frame use writeBinary().
### Example
2024-02-21 02:03:08 +00:00
```php
// 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);
```
2024-02-21 20:34:37 +00:00
### Server Events
#### connect
This event is emitted when a new WebSocket request has been accepted. The `WebSocketConnection` is passed as the first argument.
### WebSocketConnection events
#### ping
This event will be emitted upon receiving a frame with a ping opcode. The pong response has already been sent automatically, unless 'no_auto_pong' is set in the context.
#### pong
This event will be emitted upon receiving a frame with a pong opcode.
#### text
This event will be emitted when a text data frame have been received and decoded.
#### binary
This event will be emitted when a binary data frame have been received and decoded.
#### close
#### error