onMessage
Description:
callback Connection::$onMessage
The function is the same as the Worker::$onMessage callback, with the distinction that it is only effective for the current connection, which means the onMessage callback can be set for a specific connection.
Example
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('websocket://0.0.0.0:8484');
// When a client connects
$worker->onConnect = function(TcpConnection $connection)
{
// Set connection's onMessage callback
$connection->onMessage = function(TcpConnection $connection, $data)
{
var_dump($data);
$connection->send('receive success');
};
};
// Run the worker
Worker::runAll();
The effect of the above code is the same as the one below.
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('websocket://0.0.0.0:8484');
// Set onMessage callback for all connections directly
$worker->onMessage = function(TcpConnection $connection, $data)
{
var_dump($data);
$connection->send('receive success');
};
// Run the worker
Worker::runAll();