Events.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. // 向当前client_id发送数据
  37. Gateway::sendToClient($client_id, json_encode(array(
  38. 'type' => 'init',
  39. 'client_id' => $client_id
  40. )));
  41. }
  42. /**
  43. * 当客户端发来消息时触发
  44. * @param int $client_id 连接id
  45. * @param mixed $message 具体消息
  46. */
  47. public static function onMessage($client_id, $message)
  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. }