Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
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 OpenSwoole 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 OpenSwoole\Server("127.0.0.1", 9501, OpenSwoole\Server::SIMPLE_MODE, OpenSwoole\Constant::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();
OpenSwoole\Server::__construct
OpenSwoole\Server->set
OpenSwoole\Server->on
OpenSwoole\Server->listen
OpenSwoole\Server->addListener
OpenSwoole\Server->addProcess
OpenSwoole\Server->addTimer
OpenSwoole\Server->start
OpenSwoole\Server->reload
OpenSwoole\Server->stop
OpenSwoole\Server->shutdown
OpenSwoole\Server->tick
OpenSwoole\Server->after
OpenSwoole\Server->defer
OpenSwoole\Server->clearTimer
OpenSwoole\Server->close
OpenSwoole\Server->send
OpenSwoole\Server->sendfile
OpenSwoole\Server->sendto
OpenSwoole\Server->sendwait
OpenSwoole\Server->sendMessage
OpenSwoole\Server->exist
OpenSwoole\Server->pause
OpenSwoole\Server->resume
OpenSwoole\Server->getCallback
OpenSwoole\Server->getClientInfo
OpenSwoole\Server->getClientList
OpenSwoole\Server->bind
OpenSwoole\Server->stats
OpenSwoole\Server->task
OpenSwoole\Server->taskWait
OpenSwoole\Server->taskWaitMulti
OpenSwoole\Server->taskCo
OpenSwoole\Server->finish
OpenSwoole\Server->heartbeat
OpenSwoole\Server->getLastError
OpenSwoole\Server->getSocket
OpenSwoole\Server->protect
OpenSwoole\Server->confirm
OpenSwoole\Server->getReceivedTime
OpenSwoole\Server->getWorkerId
OpenSwoole\Server->getWorkerPid
OpenSwoole\Server->getWorkerStatus
OpenSwoole\Server->getManagerPid
OpenSwoole\Server->getMasterPid
Server Reaction Events
OpenSwoole\Server->on('Start', fn)
OpenSwoole\Server->on('Shutdown', fn)
OpenSwoole\Server->on('WorkerStart', fn)
OpenSwoole\Server->on('WorkerStop', fn)
OpenSwoole\Server->on('WorkerExit', fn)
OpenSwoole\Server->on('Connect', fn)
OpenSwoole\Server->on('Receive', fn)
OpenSwoole\Server->on('Packet', fn)
OpenSwoole\Server->on('Close', fn)
OpenSwoole\Server->on('Task', fn)
OpenSwoole\Server->on('Finish', fn)
OpenSwoole\Server->on('Timer', fn)
OpenSwoole\Server->on('PipeMessage', fn)
OpenSwoole\Server->on('WorkerError', fn)
OpenSwoole\Server->on('ManagerStart', fn)
OpenSwoole\Server->on('ManagerStop', fn)
OpenSwoole\Server->on('BeforeReload', fn)
OpenSwoole\Server->on('AfterReload', fn)
Event Information
When a OpenSwoole server starts, configured options set using OpenSwoole\Server->set()
are saved to OpenSwoole\Server->setting
. You can access the server configuration option values while the server is running.
For Example:
<?php
$server = new OpenSwoole\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 OpenSwoole\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, 'OpenSwoole: '.$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 OpenSwoole\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, 'OpenSwoole: '.$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 OpenSwoole\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
OpenSwoole\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
OpenSwoole\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 OpenSwoole\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 OpenSwoole\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 OpenSwoole\Server::SIMPLE_MODE
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 OpenSwoole\Server::POOL_MODE
mode allows you to.
It is possible to setup a OpenSwoole server which listens on multiple ports. You can access which ports the server is listening on via OpenSwoole\Server->ports
which is a class property and a collection of OpenSwoole\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.