Join 4,000+ others and never miss out on new tips, tutorials, and more.
4.x is outdated, please check the latest version 22.x
Latest version:
pecl install openswoole-22.1.2
<?php Swoole\WebSocket\Server->on (string $event, callable $callback)
The event name to set a callback for
Callable function for the server event type
If success, it returns true
, otherwise it returns false
Register the callback function for the WebSocket Server event.
Swoole\WebSocket\Server->on('Start', fn)
Swoole\WebSocket\Server->on('Handshake, fn)
Swoole\WebSocket\Server->on('Open, fn)
Swoole\WebSocket\Server->on('Message, fn)
Swoole\WebSocket\Server->on('Request, fn)
Swoole\WebSocket\Server->on('Close, fn)
Swoole\WebSocket\Server->on('Disconnect, fn)
The callback function on request
in Swoole\WebSocket\Server
is same as the request
callback function in the Swoole HTTP server, if it is not implemented, the server will respond with a HTTP 400 error. Read more about it here.
<?php
use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
$server = new Server("127.0.0.1", 9501);
$server->on("Start", function(Server $server)
{
echo "Swoole WebSocket Server started at 127.0.0.1:9501\n";
});
$server->on('Open', function(Server $server, Swoole\Http\Request $request)
{
echo "Connection open: {$request->fd}\n";
$server->tick(1000, function() use ($server, $request)
{
$server->push($request->fd, json_encode(["hello", time()]));
});
});
$server->on('Message', function(Server $server, Frame $frame)
{
echo "Received message: {$frame->data}\n";
$server->push($frame->fd, json_encode(["hello", time()]));
});
$server->on('Close', function(Server $server, int $fd)
{
echo "Connection close: {$fd}\n";
});
$server->on('Disconnect', function(Server $server, int $fd)
{
echo "Connection disconnect: {$fd}\n";
});
$server->start();