Event.php 3.0 KB

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