Swoole server methods list

Table of Contents

public void Swoole\Server::addlistener ( string $host , integer $port , string $socket_type )

Alias: swoole_server->addListener( string $host , integer $port , string $socket_type )

<?php
mixed swoole_server->addListener(string $host, int $port, $type = SWOOLE_SOCK_TCP);

Add more listening IP or port for the server. The connection information can be acccessed by $server->connection_info() when the server has started. By the connection information, you can distinguish the source port of the connection.

Parameters

Return

The swoole_server_port object

Example

<?php
$server->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP);
$server->addlistener("192.168.1.100", 9503, SWOOLE_SOCK_TCP);
$server->addlistener("0.0.0.0", 9504, SWOOLE_SOCK_UDP);
//UnixSocket Stream
$server->addlistener("/var/run/myserv.sock", 0, SWOOLE_UNIX_STREAM);
//TCP + SSL
$server->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP | SWOOLE_SSL); 
//Listen on a random port
$port = $server->addListener("0.0.0.0", 0, SWOOLE_SOCK_TCP);
echo $port->port;

public boolean Swoole\Server::addProcess ( swoole_process $process )

Alias: swoole_server->addProcess( swoole_process $process )

<?php
bool swoole_server->addProcess(swoole_process $process)

Add a user defined child process to the server. The process can be used as monitoring or other tasks.

Parameter

Return

The return value indicates the result of add proccess to swoole server.

Example:
<?php
$server = new swoole_server('127.0.0.1', 9501);

$process = new swoole_process(function($process) use ($server) {
    while (true) {
        $msg = $process->read();
        foreach($server->connections as $conn) {
            $server->send($conn, $msg);
        }
    }
});

$server->addProcess($process);

$server->on('receive', function ($serv, $fd, $from_id, $data) use ($process) {
    // send the data received to all the child processes
    $process->write($data);
});

$server->start();

public ReturnType Swoole\Server::after ( integer $after_time_ms , callable $callback [, string $param ] )

Alias: swoole_server->after( integer $after_time_ms , callable $callback [, string $param ] )

int swoole_server->after(int $after_time_ms, mixed $callback_function)

Trigger a one time tick in the future. Alias of function swoole_timer_after(). You can remove the timer later by calling swoole_timer_clear

Parameter

Return

the timer id which uniquely identifies the timer

Example

public boolean Swoole\Server::bind ( integer $fd , integer $uid )

Alias: swoole_server->bind( integer $fd , integer $uid )

<?php
bool swoole_server->bind(int $fd, int $uid)

Bind the fd with system user UID.

The dispatch of different socket connection to the swoole server is influenced by the configuration of dispatch_mode

In the default dispatch_mode which is 2, the socket connection may be dispatched to different worker process after reconnetion. You can set the configuration of dispatch_mode to 5 and call swoole_server->bind to bind a uid number to socket connection. And then the same uid socket connection will be dispatched to the same worker process.

Parameter

Return

The result of binding

Example

public void Swoole\Server::clearTimer ( integer $timer_id )

Alias: swoole_server->clearTimer( integer $timer_id )

<?php
void swoole_server->clearTimer(int $timer_id)

Cancel the timer tick or one time tick. Alias of function swoole_timer_clear.

Parameter

Return

void

Example

$timer_id = $server->tick(1000, function ($id) use ($server) {
    $server->clearTimer($id);
});

public bool Swoole\Client::close ([ bool $force ] )

Alias: swoole_server->close([ bool $force ] )

Close the connection to the remote TCP socket and emit Close event.

Parameter

Return

the result of close the connection

Example

public array Swoole\Server::connection_info ( integer $fd [, integer $reactor_id ] )

Alias: swoole_server->connection_info( integer $fd [, integer $reactor_id ] )

Prototype

<?php
mixed swoole_server->connection_info(int $fd, int $from_id, bool $ignore_close = false)

Get the connection info, alias of function swoole_server->getClientInfo().

Parameter

Return

The array of information of the $fd client

if the $fd client dosen't exist, the result is false

Example

<?php
$fdinfo = $serv->connection_info($fd);
var_dump($fdinfo);
array(5) {
  ["from_id"]=>
  int(3)
  ["server_fd"]=>
  int(14)
  ["server_port"]=>
  int(9501)
  ["remote_port"]=>
  int(19889)
  ["remote_ip"]=>
  string(9) "127.0.0.1"
  ["connect_time"]=>
  int(1390212495)
  ["last_time"]=>
  int(1390212760)
}

$udp_client = $serv->connection_info($fd, $from_id);
var_dump($udp_client);

public array Swoole\Server::connection_list ( integer $start_fd [, integer $pagesize ] )

Alias: swoole_server->connection_list( integer $start_fd [, integer $pagesize ] )

Get the list of all the TCP connections for all the workers.

this method is besed on the shared memory and is fast.

Parameter

Return

The array list of the $fd client

If fail, the result is FALSE.

Example

<?php
$start_fd = 0;
while(true)
{
    $conn_list = $serv->connection_list($start_fd, 10);
    if($conn_list===false or count($conn_list) === 0)
    {
        echo "finish\n";
        break;
    }
    $start_fd = end($conn_list);
    var_dump($conn_list);
    foreach($conn_list as $fd)
    {
        $serv->send($fd, "broadcast");
    }
}

public Swoole\Server::__construct ( string $host [, integer $port [, integr $mode [, integer $sock_type ]]] )

Alias: swoole_server::__construct ( string $host [, integer $port [, integr $mode [, integer $sock_type ]]] )

Construct a swoole server object

Parameter

Return

The swoole_server object

Example:

Listen on a random port:

The swoole supports the feature of listening on a random port. When the argument $port isn't seted or is 0, the swoole will choose a random and available port to listen on. You can use $server->port to listen on.

<?php
$http = new swoole_http_server("127.0.0.1");

$http->on('request', function ($request, $response) {
    $response->header("Content-Type", "text/html; charset=utf-8");
    $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});

$http->start();
Listen on a port defined in systemd

The swoole-1.9.7 adds the support for systemd socket. The port listened on can be setted by the configuration of systemd.

swoole.socket

[Unit]
Description=Swoole Socket

[Socket]
ListenStream=9501
Accept=false
[Install]
WantedBy = sockets.target

swoole.service

[Service]
Type=forking
PIDFile=/var/run/swoole.pid
ExecStart=/usr/bin/php /var/www/swoole/server.php
ExecStop=/bin/kill $MAINPID
ExecReload=/bin/kill -USR1 $MAINPID

[Install]
WantedBy = multi-user.target

server.php

$http = new swoole_http_server("systemd");

$http->set([
    'daemonize' => true,
    'pid_file' => '/var/run/swoole.pid',
]);

$http->on('request', function ($request, $response) {
    $response->header("Content-Type", "text/html; charset=utf-8");
    $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});

$http->start();

Start the systemd service

sudo systemctl enable swoole.socket
sudo systemctl start swoole.socket
sudo systemctl start swoole.service

public void Swoole\Server::defer ( callable $callback )

Alias: swoole_server->defer( callable $callback )

Delay execution of the callback function at the end of current EventLoop. Alias of function swoole_event_defer().

Parameter

Return

void

Example

function query($server, $db) {
    $server->defer(function() use ($db) {
        $db->close();
    });
}

public boolean Swoole\Server::exist ( integer $fd )

Alias: swoole_server->exist( integer $fd )

Check whether the $fd which indicates a TCP client is existed.

Parameter

Return

the existence of $fd client

Example

public void Swoole\Server::finish ( string $data )

Alias: swoole_server->finish( string $data )

Used in task process for sending result to the worker process when the task is finished.

Parameter

Return

Example

public integer Swoole\Server::getLastError ( void )

Alias: swoole_server->getLastError()

Get the error code of the most recent error.

Parameter

void

Return

The error code

Error codes:

Example

public mixed Swoole\Server::getLastError()

Alias: swoole_server->getSocket()

Prototype

resource swoole_server->getSocket()

Get socket and update the options of the socket.

This method is based on the extension sockets and it needs to add the compiling configuration --enable-sockets

Parameter

void

Return

The handler of sockets resource

Example

<?php
$socket = $server->getSocket();
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

Multi cast example:

<?php
$server = new swoole_server('0.0.0.0', 9905, SWOOLE_BASE, SWOOLE_SOCK_UDP);
$server->set(['worker_num' => 1]);
$socket = $server->getSocket();

$ret = socket_set_option(
    $socket,
    IPPROTO_IP,
    MCAST_JOIN_GROUP,
    array('group' => '10.0.0.5', 'interface' => 'eth0')
);

if ($ret === false)
{
    throw new RuntimeException('Unable to join the multicast group');
}

$server->on('Packet', function (swoole_server $serv, $data, $addr)
{
    $serv->sendto($addr['address'], $addr['port'], "Swoole: $data");
    var_dump( $addr, strlen($data));
});

$server->start();

public mixed Swoole\Server::heartbeat ( boolean $if_close_connection )

Alias: swoole_server->heartbeat( boolean $if_close_connection )

Check status of all the connections of the server. Optionally close the idle and timeout connections.

Parameter

Return

The array of connections

Example

public boolean Swoole\Server::listen ( string $host , integer $port , string $socket_type )

Alias: swoole_server->listen( string $host , integer $port , string $socket_type )

Alias of bool swoole_server->addlistener(string $host, int $port, int $type);

public void Swoole\Server::on ( string $event_name , callable $callback )

Alias: swoole_server->on ( string $event_name , callable $callback )

Register callback function for the event

Parameter

Check the full list of events

Check the four types of callbacks

Return

The result if it has been registered successfully

Example

<?php
$server = new swoole_server("127.0.0.1", 9501);
$server->on('connect', function ($server, $fd){
    echo "New connection established: #{$fd}.\n";
});
$server->on('receive', function ($server, $fd, $from_id, $data) {
    $server->send($fd, "Echo to #{$fd}: \n".$data);
    $server->close($fd);
});
$server->on('close', function ($server, $fd) {
    echo "Connection closed: #{$fd}.\n";
});
$server->start();

public void Swoole\Server::pause ( integer $fd )

Alias: swoole_server->pause( integer $fd )

Pause the data receiving for the $fd client.

Only available in SWOOLE_BASE mode.

Parameter

Return

The result of pausing

Example

public void Swoole\Server::protect ( integer $fd [, boolean $is_protected ] )

Alias: swoole_server->protect( integer $fd [, boolean $is_protected ] )

Protect the $fd from being closed by the thread of checking heart beat

Parameter

Return

Example

public boolean Swoole\Server::reload ( void )

Alias: swoole_server->reload()

Gracefully restart all the worker processes and reload the PHP files.

Parameter

Return

The result if it has been reloaded successfully

Example

Restart all the worker processes by signal

kill -USR1 MASTER_PID

Only restart the task processes by signal

kill -USR2 MASTER_PID

Get all the files loaded before the worker started

<?php
$server->on('WorkerStart', function($serv, $workerId) {
    var_dump(get_included_files());
});

When using APC/OpCache

public void Swoole\Server::resume ( integer $fd )

Alias: swoole_server->resume( integer $fd )

Resume the data receiving for the $fd client..

Only available in SWOOLE_BASE mode.

Parameter

Return

The result of resuming

Example

public boolean Swoole\Server::send ( integer $fd , string $data [, integer $reactor_id ] )

Alias: swoole_server->send( integer $fd , string $data [, integer $reactor_id ] )

Send data to the remote TCP socket.

Parameter

Return

the result of send data to the client

If the result is false, you can call the method $server->getLastError() to get the error code.

Example

public boolean Swoole\Server::sendMessage ( integer $worker_id , string $data )

Alias: swoole_server->sendMessage( integer $worker_id , string $data )

Send message to worker processes by ID. This message will trigger the event of pipe message and the process which has received this message would call the callback function registered for pipe message.

There is no length limit for the message, but the server will use the temporary file in the memory if the length of file is bigger than 8K In the task worker process, sendMessage is blocking In the worker process, sendMessage is async.

Parameter

Return

The result of send message to worker

Example

<?php
$serv = new swoole_server("0.0.0.0", 9501);
$serv->set(array(
    'worker_num' => 2,
    'task_worker_num' => 2,
));
$serv->on('pipeMessage', function($serv, $src_worker_id, $data) {
    echo "#{$serv->worker_id} message from #$src_worker_id: $data\n";
});
$serv->on('task', function ($serv, $task_id, $from_id, $data){
    var_dump($task_id, $from_id, $data);
});
$serv->on('finish', function ($serv, $fd, $from_id){

});
$serv->on('receive', function (swoole_server $serv, $fd, $from_id, $data) {
    if (trim($data) == 'task')
    {
        $serv->task("async task coming");
    }
    else
    {
        $worker_id = 1 - $serv->worker_id;
        $serv->sendMessage("hello task process", $worker_id);
    }
});

$serv->start();

public boolean Swoole\Server::sendfile ( integer $fd , string $filename [, integer $offset ] )

Alias: swoole_server->sendfile( integer $fd , string $filename [, integer $offset ] )

Send large size data or files to the remote TCP socket. A wrapper of the sendfile system call.

Parameter

Return

The timer id which uniquely identifies the timer

Example

<?php
$server->sendfile($fd, __DIR__.'/test.jpg');

public boolean Swoole\Server::sendto ( string $ip , integer $port , string $data [, string $server_socket ] )

Alias: swoole_server->sendto( string $ip , integer $port , string $data [, string $server_socket ] )

Send data to the remote UDP address.

To use swoole_server->sendto, the swoole server has to listen the port of UDP To use swoole_server->sendto to send data to IPV6, the swoole server has to listen the port of UDP6

Parameter

Return

The result of send data

Example

<?php
$server->sendto('220.181.57.216', 9502, "hello world");

$server->sendto('2600:3c00::f03c:91ff:fe73:e98f', 9501, "hello world");

public boolean Swoole\Server::sendwait ( integer $fd , string $data )

Alias: swoole_server->sendwait( integer $fd , string $data )

Send data to the remote socket in the blocking way.

Only available in SWOOLE_BASE mode.

Parameter

Return

The result of sending data

Example

public ReturnType Swoole\Server::set ( array $settings )

Alias: swoole_server->set( array $settings )

Set the runtime settings of the swoole server. The settings can be accessed by $server->setting when the swoole server has started.

Parameter

Setting example:

Return

void

Example

<?php
$server->set(array(
    'reactor_num' => 2, //reactor thread num
    'worker_num' => 4,    //worker process num
    'backlog' => 128,   //listen backlog
    'max_request' => 50,
    'dispatch_mode' => 1,
));

public void Swoole\Server::shutdown ( void )

Alias: swoole_server->shutdown()

Shutdown the master server process, this function can be called in worker processes.

Shutdown server by system signal SIGTERM

kill -15 MASTER_PID

Parameter

void

Return

void

Example

public void Swoole\Server::start ( void )

Alias: swoole_server->start()

Start the swoole server, it will create worker_num + 2 processes by default:

Parameter

void

Return

The result if the swoole server starts successfully

Example

<?php
$server = new swoole_server("127.0.0.1", 9501);
$server->on('connect', function ($server, $fd){
    echo "New connection established: #{$fd}.\n";
});
$server->on('receive', function ($server, $fd, $from_id, $data) {
    $server->send($fd, "Echo to #{$fd}: \n".$data);
    $server->close($fd);
});
$server->on('close', function ($server, $fd) {
    echo "Connection closed: #{$fd}.\n";
});
$server->start();

public array Swoole\Server::stats ( void )

Alias: swoole_server->stats()

Get the TCP connections stats of the current server.

Parameter

void

Return

The array of connections stats of the current server

<?php
array (
  'start_time' => 1409831644,  // the time of server since start
  'connection_num' => 1,       // the number of current connections 
  'accept_count' => 1,         // the number of connections accepted
  'close_count' => 0,          // the number of connections closed
  'tasking_num' => 1,          // the number of task which is queuing up
  'request_count' => 11,       // the number of request received
  'worker_request_count'       // the number of request received by the current worker
  'task_queue_num' => 10,      // the number of task which is in queue of task
  'task_queue_bytes' => 65536, // the number of bytes which is the space occupied by the queue of task
);

Example

public boolean Swoole\Server::stop ([ integer $worker_id ] )

Alias: swoole_server->stop([ integer $worker_id ] )

Stop current worker process or worker process by ID, this will emit 'WorkerStop' event and trigger the WorkerStop callback function.

Parameter

Return

The result if the swoole server starts successfully

Example

<?php
$server = new swoole_server("127.0.0.1", 9501);
$server->on('connect', function ($server, $fd){
    echo "New connection established: #{$fd}.\n";
});
$server->on('receive', function ($server, $fd, $from_id, $data) {
    if(trim($data) == "stop")
    {
        $server->stop();
    }
    else
    {
        $server->send($fd, "Echo to #{$fd}: \n".$data);
        $server->close($fd);
    }
});

$server->on('WorkerStop', function($server, $worker_id){
    echo $worker_id . " stop\n";
});

$server->on('close', function ($server, $fd) {
    echo "Connection closed: #{$fd}.\n";
});
$server->start();

public mixed Swoole\Server::task ( string $data [, integer $dst_worker_id [, callable $callback ]] )

Alias: swoole_server->task( string $data [, integer $dst_worker_id [, callable $callback ]] )

Send data to the task worker processes.

To call this method, it needs to set the configuration of task_worker_num and the callback function of onTask and onFinish This method is non-blocking and return immediately after sending the task data to the pool of task worker.

Parameter

Return

If the call of this method succeeds, the return is the task id which identifies the task If the call of this method fails, the return is false

Example

<?php
$task_id = $server->task("some data");

$server->task("taskcallback", -1, function (swoole_server $serv, $task_id, $data) {
    echo "Task Callback: ";
    var_dump($task_id, $data);
});

public void Swoole\Server::taskwait ( string $data [, float $timeout [, integer $worker_id ]] )

Alias: swoole_server->taskwait( string $data [, float $timeout [, integer $worker_id ]] )

The swoole_server->taskwait is similar to swoole_server->task. The two methods both send task data to the task worker pool to execute, but the former is blocking.

Parameter

Return

If the call of this method succeeds, the return is the result of task If the execution of this method exceeds the time of timeout, the return is false

Example

public void Swoole\Server::taskWaitMulti ( array $tasks [, double $timeout_ms ] )

Alias: swoole_server->taskWaitMulti( array $tasks [, double $timeout_ms ] )

Execute multiple tasks concurrently

Parameter

Return

If the call of this method succeeds, the return is the array of the result of tasks If the execution of some task exceeds the time of timeout, its result will not be in the return array

Example

<?php
$tasks[] = mt_rand(1000, 9999); 
$tasks[] = mt_rand(1000, 9999); 
$tasks[] = mt_rand(1000, 9999); 
var_dump($tasks);

$results = $serv->taskWaitMulti($tasks, 10.0);

if (!isset($results[0])) {
    echo "Task 1: timeout.\n";
}
if (isset($results[1])) {
    echo "Task 2: {$results[1]}\n";
}
if (isset($results[2])) {
    echo "Task 3: {$results[2]}\n";
}

public void Swoole\Server::tick ( integer $interval_ms , callable $callback )

Alias: swoole_server->tick( integer $interval_ms , callable $callback )

Trigger a timer tick by interval. Alias of function swoole_timer_tick(). You can remove the timer later by calling swoole_timer_clear

Parameter

Return

The timer id which uniquely identifies the timer

Example

Use the swoole_server->tick in onReceive

<?php
function onReceive($server, $fd, $from_id, $data) {
    $server->tick(1000, function() use ($server, $fd) {
        $server->send($fd, "hello world");
    });
}

Use the swoole_server->tick in onWorkerStart

<?php
function onWorkerStart(swoole_server $serv, $worker_id)
{
    if (!$serv->taskworker) {
        $serv->tick(1000, function ($id) {
            var_dump($id);
        });
    } else {
        $serv->addtimer(1000);
    }
}