onMessage

说明:

  1. callback Connection::$onMessage

作用与Worker::$onMessage回调相同,区别是只针对当前连接有效,也就是可以针对某个连接的设置onMessage回调。

范例

  1. use Workerman\Worker;
  2. require_once __DIR__ . '/Workerman/Autoloader.php';
  3. $worker = new Worker('websocket://0.0.0.0:8484');
  4. // 当有客户端连接事件时
  5. $worker->onConnect = function($connection)
  6. {
  7. // 设置连接的onMessage回调
  8. $connection->onMessage = function($connection, $data)
  9. {
  10. var_dump($data);
  11. $connection->send('receive success');
  12. };
  13. };
  14. // 运行worker
  15. Worker::runAll();

上面代码与下面的效果是一样的

  1. use Workerman\Worker;
  2. require_once __DIR__ . '/Workerman/Autoloader.php';
  3. $worker = new Worker('websocket://0.0.0.0:8484');
  4. // 直接设置所有连接的onMessage回调
  5. $worker->onMessage = function($connection, $data)
  6. {
  7. var_dump($data);
  8. $connection->send('receive success');
  9. };
  10. // 运行worker
  11. Worker::runAll();