2.0.0
Changes since RC3
- Renamed
EndpointtoGateway. An alias toEndpointis provided for compatibility. - Renamed
WebsocketObservertoWebsocketServerObserver.
Upgrading from v1.x to v2.0
This library has been refactored to use the new amphp/websocket library containing components that can be shared between server and clients.
Websocket is now a final class that requires an instance of ClientHandler, which has two methods to handle client handshakes and the client connection.
handleHandshake(): This method is invoked when a WebSocket connection attempt is made. The application may alter the given Response to deny the connection attempt or set application-specific headers.handleClient(): This method is invoked upon a successful WebSocket connection. This method should use a loop to receive messages from the WebSocket connection.
use Amp\Http\Server\Request;
use Amp\Http\Server\Response;
use Amp\Http\Status;
use Amp\Success;
use Amp\Websocket\Client;
use Amp\Websocket\Server\ClientHandler;
use Amp\Websocket\Server\Gateway;
use Amp\Websocket\Server\Websocket;
$websocket = new Websocket(new class implements ClientHandler {
public function handleHandshake(Gateway $gateway, Request $request, Response $response): Promise
{
if (!\in_array($request->getHeader('origin'), ['http://localhost:1337', 'http://127.0.0.1:1337', 'http://[::1]:1337'], true)) {
return $gateway->getErrorHandler()->handleError(Status::FORBIDDEN, 'Origin forbidden', $request);
}
return new Success($response);
}
public function handleClient(Gateway $gateway, Client $client, Request $request, Response $response): Promise
{
return Amp\call(function () use ($gateway, $client) {
while ($message = yield $client->receive()) {
\assert($message instanceof Message);
$gateway->broadcast(\sprintf('%d: %s', $client->getId(), yield $message->buffer()));
}
});
}
});WebSocket clients are now represented by a Client object. This object contains several methods for getting information about the client and for sending messages to a single client.
Servers can send to multiple clients using Gateway::broadcast() and Gateway::multicast() (plus binary versions, Gateway::broadcastBinary() and Gateway::multicastBinary()). A Gateway instance is provided to ClientHandler::handleHandshake() and ClientHandler::handleClient().