Context.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace GatewayClient;
  3. /**
  4. * This file is part of workerman.
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the MIT-LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @author walkor<walkor@workerman.net>
  11. * @copyright walkor<walkor@workerman.net>
  12. * @link http://www.workerman.net/
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. /**
  16. * 上下文 包含当前用户uid, 内部通信local_ip local_port socket_id ,以及客户端client_ip client_port
  17. */
  18. class Context
  19. {
  20. /**
  21. * 内部通讯id
  22. * @var string
  23. */
  24. public static $local_ip;
  25. /**
  26. * 内部通讯端口
  27. * @var int
  28. */
  29. public static $local_port;
  30. /**
  31. * 客户端ip
  32. * @var string
  33. */
  34. public static $client_ip;
  35. /**
  36. * 客户端端口
  37. * @var int
  38. */
  39. public static $client_port;
  40. /**
  41. * client_id
  42. * @var string
  43. */
  44. public static $client_id;
  45. /**
  46. * 连接connection->id
  47. * @var int
  48. */
  49. public static $connection_id;
  50. /**
  51. * 旧的session
  52. *
  53. * @var string
  54. */
  55. public static $old_session;
  56. /**
  57. * 编码session
  58. * @param mixed $session_data
  59. * @return string
  60. */
  61. public static function sessionEncode($session_data = '')
  62. {
  63. if ($session_data !== '') {
  64. return serialize($session_data);
  65. }
  66. return '';
  67. }
  68. /**
  69. * 解码session
  70. * @param string $session_buffer
  71. * @return mixed
  72. */
  73. public static function sessionDecode($session_buffer)
  74. {
  75. return unserialize($session_buffer);
  76. }
  77. /**
  78. * 清除上下文
  79. * @return void
  80. */
  81. public static function clear()
  82. {
  83. static::$local_ip = static::$local_port = static::$client_ip = static::$client_port =
  84. static::$client_id = static::$connection_id = static::$old_session = null;
  85. }
  86. /**
  87. * 通讯地址到client_id的转换
  88. * @return string
  89. */
  90. public static function addressToClientId($local_ip, $local_port, $connection_id)
  91. {
  92. return bin2hex(pack('NnN', $local_ip, $local_port, $connection_id));
  93. }
  94. /**
  95. * client_id到通讯地址的转换
  96. * @return array
  97. */
  98. public static function clientIdToAddress($client_id)
  99. {
  100. if (strlen($client_id) !== 20) {
  101. throw new \Exception("client_id $client_id is invalid");
  102. }
  103. return unpack('Nlocal_ip/nlocal_port/Nconnection_id' ,pack('H*', $client_id));
  104. }
  105. }