https://github.com/valtzu/guzzle-websocket-middleware
Connect to a WebSocket server using Guzzle HTTP client
https://github.com/valtzu/guzzle-websocket-middleware
guzzle guzzle-middleware php8 websocket ws wss
Last synced: 16 days ago
JSON representation
Connect to a WebSocket server using Guzzle HTTP client
- Host: GitHub
- URL: https://github.com/valtzu/guzzle-websocket-middleware
- Owner: valtzu
- License: mit
- Created: 2024-05-09T18:06:23.000Z (12 months ago)
- Default Branch: main
- Last Pushed: 2025-03-27T16:04:32.000Z (about 1 month ago)
- Last Synced: 2025-03-27T17:23:49.363Z (about 1 month ago)
- Topics: guzzle, guzzle-middleware, php8, websocket, ws, wss
- Language: PHP
- Homepage: https://packagist.org/packages/valtzu/guzzle-websocket-middleware
- Size: 22.5 KB
- Stars: 5
- Watchers: 1
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
## Connect to WebSocket endpoints with Guzzle HTTP client
**NOTE:** Only `StreamHandler` supported (so not `CurlHandler`!).
### Installation
```
composer require valtzu/guzzle-websocket-middleware
```### Usage
Guzzle's `synchronous` option is used to configure the stream blocking option.
#### Synchronous usage
```php
$handlerStack = new HandlerStack(new StreamHandler());
$handlerStack->unshift(new WebSocketMiddleware());$guzzle = new Client(['handler' => $handlerStack]);
$handshakeResponse = $guzzle->request('GET', 'wss://ws.postman-echo.com/raw');
$ws = $handshakeResponse->getBody();$ws->write("Hello world");
$helloWorld = $ws->read(); // This will block until the reply frame is received
```#### Asynchronous usage
```php
$handlerStack = new HandlerStack(new StreamHandler());
$handlerStack->unshift(new WebSocketMiddleware());$guzzle = new Client(['handler' => $handlerStack]);
$handshakeResponse = $guzzle->requestAsync('GET', 'wss://ws.postman-echo.com/raw')->wait();
$ws = $handshakeResponse->getBody();$ws->write("Hello world");
$helloWorld = $ws->read(); // Here you may get an empty string if data wasn't received yet
```#### Connection upkeep / ping-pong
Whenever you read from a websocket stream, instead of receiving a text/binary frame, you may receive "ping" instead.
When this happens, we automatically respond with "pong". However, due to being PHP (usually) being single-threaded,
this means that you must make sure `read` (even with `0` length) is done frequently enough.It's also possible to manually send a ping – however, it does not wait for the other party to reply.
```php
$ws->ping();
```### Contributing
1. If you have an issue with package, or you have a feature request, please open an issue
1. If you want to contribute code, you may submit a Pull Request. Just remember to add tests.