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
<?php OpenSwoole\Server->sendMessage(string $message, int $workerId): bool
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
The worker ID to communicate with over a pipe message event.
If success, it returns 'true', otherwise it returns false
.
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:
sendMessage
is blockingsendMessage
is async, non-blocking callsendMessage
is blockingworker_num
+ task_worker_num
- 1)However, there are some cases where OpenSwoole 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.
<?php
$server = new OpenSwoole\Server("0.0.0.0", 9501);
$server->set([
'worker_num' => 2,
'task_worker_num' => 2,
]);
$server->on('PipeMessage', function(OpenSwoole\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 (OpenSwoole\Server $server, int $taskId, mixed $data)
{
// ...
});
$server->on('Receive', function (OpenSwoole\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.