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::__construct(string $host, int $port)
The IP address of the server to listen on
The port of the server (root privilege required if the port number is less than 1024)
A Swoole\WebSocket\Server object if successful
Create a new WebSocket server. Provide the IP and port you want the server to listen on and Swoole will create a Swoole\WebSocket\Server
object for you in return.
The Swoole\WebSocket\Server
is a sub-class of Swoole\Server
and inherits some features form Swoole\Http\Server
as well.
You can use the methods from the Swoole\Server
within a WebSocket Server.
$Swoole\WebSocket\server->push(...)
to send WebSocket data, the Swoole\Server->send(...)
method is used for traditional TCP data transmission.<?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->start();