Event.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /**
  3. *
  4. *
  5. * @author walkor <workerman.net>
  6. *
  7. */
  8. require_once ROOT_DIR . '/Lib/Gateway.php';
  9. require_once ROOT_DIR . '/Protocols/JsonProtocol.php';
  10. class Event
  11. {
  12. /**
  13. * 网关有消息时,判断消息是否完整
  14. */
  15. public static function onGatewayMessage($buffer)
  16. {
  17. return JsonProtocol::check($buffer);
  18. }
  19. /**
  20. * 此链接的用户没调用GateWay::notifyConnectionSuccess($uid);前(即没有得到验证),都触发onConnect
  21. * 已经调用GateWay::notifyConnectionSuccess($uid);的用户有消息时,则触发onMessage
  22. * @param string $message 一般是传递的账号密码等信息
  23. * @return void
  24. */
  25. public static function onConnect($message)
  26. {
  27. /*
  28. * 通过message验证用户,并获得uid。
  29. * 一般流程这里$message应该包含用户名 密码,然后根据用户名密码从数据库中获取uid
  30. * 这里只是根据时间戳生成uid,高并发下会有小概率uid冲突
  31. */
  32. $uid = self::checkUser($message);
  33. // 不合法踢掉
  34. if(!$uid)
  35. {
  36. // 踢掉
  37. return GateWay::kickCurrentUser();
  38. }
  39. // [这步是必须的]合法,记录uid到gateway通信地址的映射
  40. GateWay::storeUid($uid);
  41. // [这步是必须的]发送数据包到address对应的gateway,确认connection成功
  42. GateWay::notifyConnectionSuccess($uid);
  43. // 向当前用户发送uid
  44. GateWay::sendToCurrentUid(JsonProtocol::encode(array('uid'=>$uid)));
  45. // 广播所有用户,xxx connected
  46. GateWay::sendToAll(JsonProtocol::encode(array('from_uid'=>'SYSTEM', 'message'=>"$uid come \n", 'to_uid'=>'all')));
  47. }
  48. /**
  49. * 当用户断开连接时触发的方法
  50. * @param string $address 和该用户gateway通信的地址
  51. * @param integer $uid 断开连接的用户id
  52. * @return void
  53. */
  54. public static function onClose($uid)
  55. {
  56. // [这步是必须的]删除这个用户的gateway通信地址
  57. GateWay::deleteUidAddress($uid);
  58. // 广播 xxx 退出了
  59. GateWay::sendToAll(JsonProtocol::encode(array('from_uid'=>'SYSTEM', 'message'=>"$uid logout\n", 'to_uid'=>'all')));
  60. }
  61. /**
  62. * 有消息时触发该方法
  63. * @param int $uid 发消息的uid
  64. * @param string $message 消息
  65. * @return void
  66. */
  67. public static function onMessage($uid, $message)
  68. {
  69. $message_data = JsonProtocol::decode($message);
  70. // 向所有人发送
  71. if($message_data['to_uid'] == 'all')
  72. {
  73. return GateWay::sendToAll($message);
  74. }
  75. // 向某个人发送
  76. else
  77. {
  78. return GateWay::sendToUid($message_data['to_uid'], $message);
  79. }
  80. }
  81. /**
  82. * 用户第一次链接时,根据用户传递的消息(一般是用户名 密码)返回当前uid
  83. * 这里只是返回了时间戳相关的一个数字
  84. * @param string $message
  85. * @return number
  86. */
  87. protected static function checkUser($message)
  88. {
  89. return substr(strval(microtime(true)), 3, 10)*100;
  90. }
  91. }