Event.php 3.1 KB

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