Swoole\Server->on('receive', fn)

Declaration

<?php
Swoole\Server->on('receive', callback $callback)

Parameters

event

The event name

callback

callback function

Return

success

if success, it returns TRUE, otherwise it returns FALSE.

Description

Executue the callback function when the Server is receving TCP packages.

The callback function registered on the event receive is executed in the Worker Process which is receiving data.

Callback function

<?php
function (Swoole\Server $server, int $fd, int $reactor_id, string $data) {

}
  • $fd If Swoole Server is in TCP mode, it's fd of the Client. If Swoole Server is in UDP mode, it's the value calculated based on Client IP.
  • $reactor_id If the Swoole Server is in TCP mode, it's the ID of reactor thread. If the Swoole Server is in UDP mode, it's the value calculated based on Client PORT.
  • $data the data received from Client side. If there is no TCP protocol configuration, the max length of data that worker process could receive is 64KB.

Under the TCP mode, there is no boundary of the data transmits between Client and Server. It is necessary to set the configuration eof_check, length_check or http_protocol about how to split the stream into package or convert the data stream into package manually.

Protocol parsing and data stream splitting

Swoole Server has the build-in parsers to parse the HTTP, HTTP2, WebSocket, MQTT packages, the packages are then passed into receive callback function:

  • open_http_protocol
  • open_http2_protocol
  • open_websocket_protocol
  • open_mqtt_protocol

You can enable these parsers on the server, for example:

<?php
$server->set([
  'open_mqtt_protocol' => true
]);

Other parsering related settings:

open_length_check

By enabling open_length_check, you have to set package_max_length. Then the parser ignores the data exceeding package_max_length, and close the connection.

open_eof_check

Ignore the data after EOF. Then the parser ignores the data exceeding package_max_length, and close the connection.

open_eof_split

Split the data stream into packages with EOF. You can set the EOF to be \r\n or other string.

Data transformation

Transform the data into the $fd and reactor_id of receive callback function

<?php
$fd = unpack('L', pack('N', ip2long($addr['address'])))[1];
$reactor_id = ($addr['server_socket'] << 16) + $addr['port'];

Example

<?php
$server = new Swoole\Server("127.0.0.1", 9501);
$server->on('start', function ($server){
    echo "Server is started.\n";
});
$server->on('shutdown', function ($server){
    echo "Server is shuttng down.\n";
});
$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();