This library contains WebSocket client and server for PHP.
Replaces textalk/websocket.
The client and server provides methods for reading and writing to WebSocket streams.
This repo replaces the abandoned textalk/websocket repo
and is maintained by Sören Jensen, who has been maintaining the original since v1.3.
Preferred way to install is with Composer.
composer require phrity/websocket
The client can read and write on a WebSocket stream. It internally supports Upgrade handshake and implicit close and ping/pong operations.
Set up a WebSocket Client for request/response strategy.
$client = new WebSocketClient("wss://echo.websocket.org/");
$client
// Add standard middlewares
->addMiddleware(new WebSocketMiddlewareCloseHandler())
->addMiddleware(new WebSocketMiddlewarePingResponder())
;
// Send a message
$client->text("Hello WebSocket.org!");
// Read response (this is blocking)
$message = $client->receive();
echo "Got message: {$message->getContent()} n";
// Close connection
$client->close();Set up a WebSocket Client for continuous subscription
$client = new WebSocketClient("wss://echo.websocket.org/");
$client
// Add standard middlewares
->addMiddleware(new WebSocketMiddlewareCloseHandler())
->addMiddleware(new WebSocketMiddlewarePingResponder())
// Listen to incoming Text messages
->onText(function (WebSocketClient $client, WebSocketConnection $connection, WebSocketMessageMessage $message) {
// Act on incoming message
echo "Got message: {$message->getContent()} n";
// Possibly respond to server
$client->text("I got your your message");
})
->start();The server is a multi connection, listening server. It internally supports Upgrade handshake and implicit close and ping/pong operations.
Set up a WebSocket Server for continuous listening
$server = new WebSocketServer();
$server
// Add standard middlewares
->addMiddleware(new WebSocketMiddlewareCloseHandler())
->addMiddleware(new WebSocketMiddlewarePingResponder())
// Listen to incoming Text messages
->onText(function (WebSocketServer $server, WebSocketConnection $connection, WebSocketMessageMessage $message) {
// Act on incoming message
echo "Got message: {$message->getContent()} n";
// Possibly respond to client
$connection->text("I got your your message");
})
->start();ISC License