callback Worker::$onMessage

Callback function triggered when the client sends data through the connection (when Workerman receives data).

Callback function parameters


Connection object, i.e. TcpConnection instance, used to operate client connections, such as sending data, closing the connection, etc.


Data sent from the client connection. If the Worker specifies a protocol, then $data is the decoded data corresponding to the protocol. The data type depends on the implementation of the decode() method in the protocol. For example, for websocket, text, frame, the data type is a string, and for the HTTP protocol it is a Workerman\Protocols\Http\Request object.


use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('websocket://');
$worker->onMessage = function(TcpConnection $connection, $data)
    $connection->send('receive success');
// Run the worker

Note: In addition to using an anonymous function as a callback, other callback writing methods can also be used.