Events.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. /**
  15. * 用于检测业务代码死循环或者长时间阻塞等问题
  16. * 如果发现业务卡死,可以将下面declare打开(去掉//注释),并执行php start.php reload
  17. * 然后观察一段时间workerman.log看是否有process_timeout异常
  18. */
  19. //declare(ticks=1);
  20. use \GatewayWorker\Lib\Gateway;
  21. /**
  22. * 主逻辑
  23. * 主要是处理 onConnect onMessage onClose 三个方法
  24. * onConnect 和 onClose 如果不需要可以不用实现并删除
  25. */
  26. class Events
  27. {
  28. /**
  29. * 当客户端连接时触发
  30. * 如果业务不需此回调可以删除onConnect
  31. *
  32. * @param int $client_id 连接id
  33. */
  34. public static function onConnect($client_id)
  35. {
  36. Gateway::sendToClient($client_id, json_encode(array(
  37. 'type' => 'init',
  38. 'client_id' => $client_id
  39. )));
  40. }
  41. /**
  42. * 当客户端发来消息时触发
  43. * @param int $client_id 连接id
  44. * @param mixed $message 具体消息
  45. */
  46. public static function onMessage($client_id, $message)
  47. {
  48. // 向所有人发送
  49. if(strpos($message,'get_state:')===0){
  50. $user_ids=explode(',',str_replace('get_state:','',$message));
  51. $u_state=array();
  52. foreach($user_ids as $user_id){
  53. $u_state[$user_id]=Gateway::isUidOnline('0:'.$user_id);
  54. }
  55. Gateway::sendToClient($client_id, json_encode(array(
  56. 'type' => 'get_state',
  57. 'u_state' => $u_state,
  58. )));
  59. }
  60. }
  61. /**
  62. * 当用户断开连接时触发
  63. * @param int $client_id 连接id
  64. */
  65. public static function onClose($client_id)
  66. {
  67. // 向所有人发送
  68. // GateWay::sendToAll("$client_id logout\r\n");
  69. }
  70. }