Swoole Server sendMessage()

Declaration

<?php
Swoole\Server->sendMessage(string $message, int $workerId): bool

Parameters

message

The message content to send, expects a string of data, there is no limit but after 8K, a temporary file on disk will be used to queue data

workerId

The worker ID to communicate with over a pipe message event.

Return

success

If success, it returns 'true', otherwise it returns false.

Description

Send a message to a worker processes by using its ID. This message will trigger the event of PipeMessage and the process which has received this message will call the callback function registered for PipeMessage, allowing the worker to handle the data sent to it.

There is no real length limit for the message, but the server will use a temporary file, if the length of file is bigger than 8K

Things to consider:

  • In the task worker process, sendMessage is blocking
  • In the worker process, sendMessage is async, non-blocking call
  • In a user defined process, sendMessage is blocking
  • The worker ID should be collected from the server but in general the ID will be between 0 and (worker_num + task_worker_num - 1)

However, there are some cases where Swoole will convert a blocking call into a asynchronous call.

Only to be used within a task, worker process or user defined process to communicate between each other.

Example

<?php
$server = new Swoole\Server("0.0.0.0", 9501);

$server->set([
    'worker_num' => 2,
    'task_worker_num' => 2,
]);

$server->on('PipeMessage', function(Swoole\Server $server, int $srcWorkerId, mixed $data)
{
    echo "#{$server->worker_id} message from #$srcWorkerId: $data\n";
});

$server->on('Task', function ($server, $task_id, $from_id, $data)
{
    var_dump($task_id, $from_id, $data);
});

$server->on('Finish', function (Swoole\Server $server, int $taskId, mixed $data)
{
    // ...
});

$server->on('Receive', function (Swoole\Server $server, $fd, $fromId, $data)
{
    if(trim($data) == 'task')
    {
        $server->task("async task coming");
    }
    else
    {
        $worker_id = 1 - $server->worker_id;
        $server->sendMessage("hello task process", $worker_id);
    }
});

$server->start();

You must register the PipeMessage event callback when using sendMessage otherwise data will not be received and will be kept in memory, building up over time, taking up resources.

If you are using task_ipc_mode and it is set to 3, you cannot use sendMessage to talk to a specific task process.