Event.php 2.7 KB

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