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
The TCP/UDP Server provides you with the API to run TCP, UDP, Unix Socket asynchronous servers. It supports IPv4, IPv6, one Way, two Way SSL and TLS Encryption. It is simple and quick to get a full TCP/UDP server setup and you don't need to know the internal implementations, you only have to write your application business logic for each server event in the callback functions. You can use the Swoole Server to conveniently create a TCP/UDP server from your PHP scripts, there is no requirement to use Nginx although it might be recommended to use a proxy pass through.
Notice: The Server API can only be used in PHP CLI mode
<?php
$server = new Swoole\Server("127.0.0.1", 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);
<?php
$server->set([
'worker_num' => 4, // The number of worker processes
'daemonize' => true, // Whether to start as a daemon process
'backlog' => 128, // TCP backlog connection number
]);
<?php
$server->on('connect', function() {
// ...
});
$server->on('receive', function() {
// ...
});
$server->on('close', function() {
// ...
});
There are four types of callback functions
<?php
$server->start();
Swoole\Server::__construct
Swoole\Server->set
Swoole\Server->on
Swoole\Server->listen
Swoole\Server->addListener
Swoole\Server->addProcess
Swoole\Server->addTimer
Swoole\Server->start
Swoole\Server->reload
Swoole\Server->stop
Swoole\Server->shutdown
Swoole\Server->tick
Swoole\Server->after
Swoole\Server->defer
Swoole\Server->clearTimer
Swoole\Server->close
Swoole\Server->send
Swoole\Server->sendfile
Swoole\Server->sendto
Swoole\Server->sendwait
Swoole\Server->sendMessage
Swoole\Server->exist
Swoole\Server->pause
Swoole\Server->resume
Swoole\Server->getCallback
Swoole\Server->getClientInfo
Swoole\Server->getClientList
Swoole\Server->bind
Swoole\Server->stats
Swoole\Server->task
Swoole\Server->taskWait
Swoole\Server->taskWaitMulti
Swoole\Server->taskCo
Swoole\Server->finish
Swoole\Server->heartbeat
Swoole\Server->getLastError
Swoole\Server->getSocket
Swoole\Server->protect
Swoole\Server->confirm
Swoole\Server->getReceivedTime
Swoole\Server->getWorkerId
Swoole\Server->getWorkerPid
Swoole\Server->getWorkerStatus
Swoole\Server->getManagerPid
Swoole\Server->getMasterPid
Server Reaction Events
Swoole\Server->on('Start', fn)
Swoole\Server->on('Shutdown', fn)
Swoole\Server->on('WorkerStart', fn)
Swoole\Server->on('WorkerStop', fn)
Swoole\Server->on('WorkerExit', fn)
Swoole\Server->on('Connect', fn)
Swoole\Server->on('Receive', fn)
Swoole\Server->on('Packet', fn)
Swoole\Server->on('Close', fn)
Swoole\Server->on('Task', fn)
Swoole\Server->on('Finish', fn)
Swoole\Server->on('Timer', fn)
Swoole\Server->on('PipeMessage', fn)
Swoole\Server->on('WorkerError', fn)
Swoole\Server->on('ManagerStart', fn)
Swoole\Server->on('ManagerStop', fn)
Swoole\Server->on('BeforeReload', fn)
Swoole\Server->on('AfterReload', fn)
Event Information
When a Swoole server starts, configured options set using Swoole\Server->set()
are saved to Swoole\Server->setting
. You can access the server configuration option values while the server is running.
For Example:
<?php
$server = new Swoole\Server('127.0.0.1', 9501);
$server->set(['worker_num' => 4]);
echo $server->setting['worker_num'];
Get the main process thread ID of the master process.
You can only access this object property from the event onStart
and onWorkerStart
callbacks.
For Example:
<?php
$server = new Swoole\Server("127.0.0.1", 9501);
$server->on('start', function ($server)
{
echo $server->master_pid;
});
$server->on('receive', function ($server, $fd, $reactor_id, $data)
{
$server->send($fd, 'Swoole: '.$data);
$server->close($fd);
});
$server->start();
You can send a SIGTERM
signal to this process to shutdown the server.
Get the server manager process thread ID.
You can get this ID when inside of the onStart
and onWorkerStart
event callbacks.
For Example:
<?php
$server = new Swoole\Server("127.0.0.1", 9501);
$server->on('start', function ($server)
{
echo $server->manager_pid;
});
$server->on('receive', function ($server, $fd, $reactor_id, $data)
{
$server->send($fd, 'Swoole: '.$data);
$server->close($fd);
});
$server->start();
You can send a send SIGUSR1
to this process to reload the server application.
Get the current worker process thread ID and task worker ID.
For Example:
<?php
$server = new Swoole\Server('127.0.0.1', 9501);
$server->set([
'worker_num' => 8,
'task_worker_num' => 4,
]);
$server->on('WorkerStart', function ($server, int $workerId)
{
if($server->taskworker)
{
echo "Task worker ID:{$workerId}\n";
echo "Task worker ID:{$server->worker_id}\n";
}
else
{
echo "Worker ID:{$workerId}\n";
echo "Worker ID:{$server->worker_id}\n";
}
});
$server->on('Receive', function ($server, $fd, $reactorId, $data)
{
// ...
});
$server->on('Task', function ($server, $taskId, $reactorId, $data)
{
// ...
});
$server->start();
The server class property and $workerId
argument are the same, just different ways of accessing them. Worker process IDs will range from [0, $server->setting['worker_num']-1]
.
The task worker IDs will range from [$server->setting['worker_num'], $server->setting['worker_num'] + $server->setting['task_worker_num']]
.
Even after a worker process restart, the worker ID does not change.
Get the current worker operating system process thread ID, using posix_getpid()
will return the same value.
<?php
Swoole\Server->worker_pid: int
Determine if the current process is a task process. Useful to check if you are within a worker or task process.
<?php
Swoole\Server->taskworker: bool
Return Values
true
: Indicates that the current process is a task worker processfalse
: Indicates that the current process is a worker processYou can access all the currently connected client connections via the Swoole\Server->connections
iterator object. This iterator object should be used with a foreach
loop and allows you to access all the currently connected client file descriptors ('fds`).
For Example:
<?php
foreach ($server->connections as $fd)
{
var_dump($fd);
}
echo "Currently connected client connections: " . count($server->connections) . "\n";
This allows you to loop through all the TCP fd connections on the server. You can also use Swoole\Server->getClientList()
but this way is more recommended.
The server connections is not a PHP array, it is a iterator object, that is why a foreach
is recommended to be used.
In SWOOLE_BASE
mode, it does not support cross-process operation TCP connections, so the BASE mode can only access the current process connections
iterator, not the whole server like SWOOLE_PROCESS
mode allows you to.
It is possible to setup a Swoole server which listens on multiple ports. You can access which ports the server is listening on via Swoole\Server->ports
which is a class property and a collection of Swoole\Server\Port
objects of the current ports being used.
For Example:
<?php
$ports = $server->ports;
$ports[0]->set($settings);
$ports[1]->on('Receive', function()
{
// ...
});
foreach ($server->ports as $port)
{
var_dump($port);
}
Port zero is always the master port of the server.
Swoole provides you with some MIME helper functions to aid you when managing different MIME Types.
Since version 4.5.0
Definition:
function swoole_mime_type_add(string $suffix, string $mime_type): bool
Description:
Adds a new mime type to the built-in mime type table.
Definition:
function swoole_mime_type_set(string $suffix, string $mime_type): bool
Description:
Modify a mime type, fails if it does not exist and returns false.
Definition:
function swoole_mime_type_delete(string $suffix): bool
Description:
Delete a mime type, fails if it does not exist and returns false.
Definition:
function swoole_mime_type_get(string $filename): string
Description:
Get the mime type corresponding to the file name.
Definition:
function swoole_mime_type_exists(string $suffix): bool
Description:
Get whether the mime type corresponding to the suffix exists.