-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathGateway.php
1400 lines (1306 loc) · 48.5 KB
/
Gateway.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace GatewayClient;
use \Exception;
/**
* This file is part of workerman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<[email protected]>
* @copyright walkor<[email protected]>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
if (! class_exists(\Composer\Autoload\ClassLoader::class)) {
require_once __DIR__ . '/Context.php';
require_once __DIR__ . '/GatewayProtocol.php';
}
/**
* 数据发送相关
*/
class Gateway
{
/**
* gateway 实例
*
* @var object
*/
protected static $businessWorker = null;
/**
* 注册中心地址
*
* @var string|array
*/
public static $registerAddress = '127.0.0.1:1236';
/**
* 秘钥
* @var string
*/
public static $secretKey = '';
/**
* 链接超时时间
* @var int
*/
public static $connectTimeout = 3;
/**
* 与Gateway是否是长链接
* @var bool
*/
public static $persistentConnection = false;
/**
* 是否清除注册地址缓存
* @var bool
*/
public static $addressesCacheDisable = false;
/**
* 向所有客户端连接(或者 client_id_array 指定的客户端连接)广播消息
*
* @param string $message 向客户端发送的消息
* @param array $client_id_array 客户端 id 数组
* @param array $exclude_client_id 不给这些client_id发
* @param bool $raw 是否发送原始数据(即不调用gateway的协议的encode方法)
* @return void
* @throws Exception
*/
public static function sendToAll($message, $client_id_array = null, $exclude_client_id = null, $raw = false)
{
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_SEND_TO_ALL;
$gateway_data['body'] = $message;
if ($raw) {
$gateway_data['flag'] |= GatewayProtocol::FLAG_NOT_CALL_ENCODE;
}
if ($exclude_client_id) {
if (!is_array($exclude_client_id)) {
$exclude_client_id = array($exclude_client_id);
}
if ($client_id_array) {
$exclude_client_id = array_flip($exclude_client_id);
}
}
if ($client_id_array) {
if (!is_array($client_id_array)) {
echo new \Exception('bad $client_id_array:'.var_export($client_id_array, true));
return;
}
$data_array = array();
foreach ($client_id_array as $client_id) {
if (isset($exclude_client_id[$client_id])) {
continue;
}
$address = Context::clientIdToAddress($client_id);
if ($address) {
$key = long2ip($address['local_ip']) . ":{$address['local_port']}";
$data_array[$key][$address['connection_id']] = $address['connection_id'];
}
}
foreach ($data_array as $addr => $connection_id_list) {
$the_gateway_data = $gateway_data;
$the_gateway_data['ext_data'] = json_encode(array('connections' => $connection_id_list));
static::sendToGateway($addr, $the_gateway_data);
}
return;
} elseif (empty($client_id_array) && is_array($client_id_array)) {
return;
}
if (!$exclude_client_id) {
return static::sendToAllGateway($gateway_data);
}
$address_connection_array = static::clientIdArrayToAddressArray($exclude_client_id);
// 如果有businessWorker实例,说明运行在workerman环境中,通过businessWorker中的长连接发送数据
if (static::$businessWorker) {
foreach (static::$businessWorker->gatewayConnections as $address => $gateway_connection) {
$gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
json_encode(array('exclude'=> $address_connection_array[$address])) : '';
/** @var TcpConnection $gateway_connection */
$gateway_connection->send($gateway_data);
}
} // 运行在其它环境中,通过注册中心得到gateway地址
else {
$all_addresses = static::getAllGatewayAddressesFromRegister();
foreach ($all_addresses as $address) {
$gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
json_encode(array('exclude'=> $address_connection_array[$address])) : '';
static::sendToGateway($address, $gateway_data);
}
}
}
/**
* 向某个client_id对应的连接发消息
*
* @param string $client_id
* @param string $message
* @return void
*/
public static function sendToClient($client_id, $message)
{
return static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_SEND_TO_ONE, $message);
}
/**
* 判断某个uid是否在线
*
* @param string $uid
* @return int 0|1
*/
public static function isUidOnline($uid)
{
return (int)static::getClientIdByUid($uid);
}
public static function isUidsOnline($uids)
{
return array_map(function ($item) {
return (int) $item;
}, static::batchGetClientIdByUid($uids));
}
/**
* 判断client_id对应的连接是否在线
*
* @param string $client_id
* @return int 0|1
*/
public static function isOnline($client_id)
{
$address_data = Context::clientIdToAddress($client_id);
if (!$address_data) {
return 0;
}
$address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
if (isset(static::$businessWorker)) {
if (!isset(static::$businessWorker->gatewayConnections[$address])) {
return 0;
}
}
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_IS_ONLINE;
$gateway_data['connection_id'] = $address_data['connection_id'];
return (int)static::sendAndRecv($address, $gateway_data);
}
/**
* 获取所有在线用户的session,client_id为 key(弃用,请用getAllClientSessions代替)
*
* @param string $group
* @return array
*/
public static function getAllClientInfo($group = '')
{
echo "Warning: Gateway::getAllClientInfo is deprecated and will be removed in a future, please use Gateway::getAllClientSessions instead.";
return static::getAllClientSessions($group);
}
/**
* 获取所有在线client_id的session,client_id为 key
*
* @param string $group
* @return array
*/
public static function getAllClientSessions($group = '')
{
$gateway_data = GatewayProtocol::$empty;
if (!$group) {
$gateway_data['cmd'] = GatewayProtocol::CMD_GET_ALL_CLIENT_SESSIONS;
} else {
$gateway_data['cmd'] = GatewayProtocol::CMD_GET_CLIENT_SESSIONS_BY_GROUP;
$gateway_data['ext_data'] = $group;
}
$status_data = array();
$all_buffer_array = static::getBufferFromAllGateway($gateway_data);
foreach ($all_buffer_array as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $data) {
if ($data) {
foreach ($data as $connection_id => $session_buffer) {
$client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
if ($client_id === Context::$client_id) {
$status_data[$client_id] = (array)$_SESSION;
} else {
$status_data[$client_id] = $session_buffer ? Context::sessionDecode($session_buffer) : array();
}
}
}
}
}
return $status_data;
}
/**
* 获取某个组的连接信息(弃用,请用getClientSessionsByGroup代替)
*
* @param string $group
* @return array
*/
public static function getClientInfoByGroup($group)
{
echo "Warning: Gateway::getClientInfoByGroup is deprecated and will be removed in a future, please use Gateway::getClientSessionsByGroup instead.";
return static::getAllClientSessions($group);
}
/**
* 获取某个组的所有client_id的session信息
*
* @param string $group
*
* @return array
*/
public static function getClientSessionsByGroup($group)
{
if (static::isValidGroupId($group)) {
return static::getAllClientSessions($group);
}
return array();
}
/**
* 获取所有在线client_id数
*
* @return int
*/
public static function getAllClientIdCount()
{
return static::getClientCountByGroup();
}
/**
* 获取所有在线client_id数(getAllClientIdCount的别名)
*
* @return int
*/
public static function getAllClientCount()
{
return static::getAllClientIdCount();
}
/**
* 获取某个组的在线client_id数
*
* @param string $group
* @return int
*/
public static function getClientIdCountByGroup($group = '')
{
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_GET_CLIENT_COUNT_BY_GROUP;
$gateway_data['ext_data'] = $group;
$total_count = 0;
$all_buffer_array = static::getBufferFromAllGateway($gateway_data);
foreach ($all_buffer_array as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $count) {
if ($count) {
$total_count += $count;
}
}
}
return $total_count;
}
/**
* getClientIdCountByGroup 函数的别名
*
* @param string $group
* @return int
*/
public static function getClientCountByGroup($group = '')
{
return static::getClientIdCountByGroup($group);
}
/**
* 批量获取群组ID内客户端个数.
*/
public static function batchGetClientIdCountByGroup(array $groups): array
{
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_BATCH_GET_CLIENT_COUNT_BY_GROUP;
$gateway_data['ext_data'] = json_encode($groups);
$all_buffer_array = static::getBufferFromAllGateway($gateway_data);
$return = [];
foreach ($all_buffer_array as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $data) {
foreach ($data as $group => $count) {
if (! isset($return[$group])) {
$return[$group] = 0;
}
$return[$group] += $count;
}
}
}
return $return;
}
/**
* 获取某个群组在线client_id列表
*
* @param string $group
* @return array
*/
public static function getClientIdListByGroup($group)
{
if (!static::isValidGroupId($group)) {
return array();
}
$data = static::select(array('uid'), array('groups' => is_array($group) ? $group : array($group)));
$client_id_map = array();
foreach ($data as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $items) {
//$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
foreach ($items as $connection_id => $info) {
$client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
$client_id_map[$client_id] = $client_id;
}
}
}
return $client_id_map;
}
/**
* 获取集群所有在线client_id列表
*
* @return array
*/
public static function getAllClientIdList()
{
return static::formatClientIdFromGatewayBuffer(static::select(array('uid')));
}
/**
* 格式化client_id
*
* @param $data
* @return array
*/
protected static function formatClientIdFromGatewayBuffer($data)
{
$client_id_list = array();
foreach ($data as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $items) {
//$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
foreach ($items as $connection_id => $info) {
$client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
$client_id_list[$client_id] = $client_id;
}
}
}
return $client_id_list;
}
/**
* 获取与 uid 绑定的 client_id 列表
*
* @param string $uid
* @return array
*/
public static function getClientIdByUid($uid)
{
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_GET_CLIENT_ID_BY_UID;
$gateway_data['ext_data'] = $uid;
$client_list = array();
$all_buffer_array = static::getBufferFromAllGateway($gateway_data);
foreach ($all_buffer_array as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $connection_id_array) {
if ($connection_id_array) {
foreach ($connection_id_array as $connection_id) {
$client_list[] = Context::addressToClientId($local_ip, $local_port, $connection_id);
}
}
}
}
return $client_list;
}
/**
* 批量获取与 uid 绑定的 client_id 列表
*
* @param array $uids
* @return array
*/
public static function batchGetClientIdByUid($uids)
{
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_BATCH_GET_CLIENT_ID_BY_UID;
$gateway_data['ext_data'] = json_encode($uids);
$client_list = [];
$all_buffer_array = static::getBufferFromAllGateway($gateway_data);
foreach ($all_buffer_array as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $uid_connection_id_array) {
if ($uid_connection_id_array) {
foreach ($uid_connection_id_array as $uid => $connection_ids) {
if (! isset($client_list[$uid])) {
$client_list[$uid] = [];
}
foreach ($connection_ids as $connection_id) {
$client_list[$uid][] = Context::addressToClientId($local_ip, $local_port, $connection_id);
}
}
}
}
}
return $client_list;
}
/**
* 获取某个群组在线uid列表
*
* @param string $group
* @return array
*/
public static function getUidListByGroup($group)
{
if (!static::isValidGroupId($group)) {
return array();
}
$group = is_array($group) ? $group : array($group);
$data = static::select(array('uid'), array('groups' => $group));
$uid_map = array();
foreach ($data as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $items) {
//$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
foreach ($items as $connection_id => $info) {
if (!empty($info['uid'])) {
$uid_map[$info['uid']] = $info['uid'];
}
}
}
}
return $uid_map;
}
/**
* 获取某个群组在线uid数
*
* @param string $group
* @return int
*/
public static function getUidCountByGroup($group)
{
if (static::isValidGroupId($group)) {
return count(static::getUidListByGroup($group));
}
return 0;
}
/**
* 获取全局在线uid列表
*
* @return array
*/
public static function getAllUidList()
{
$data = static::select(array('uid'));
$uid_map = array();
foreach ($data as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $items) {
//$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
foreach ($items as $connection_id => $info) {
if (!empty($info['uid'])) {
$uid_map[$info['uid']] = $info['uid'];
}
}
}
}
return $uid_map;
}
/**
* 获取全局在线uid数
* @return int
*/
public static function getAllUidCount()
{
return count(static::getAllUidList());
}
/**
* 通过client_id获取uid
*
* @param $client_id
* @return mixed
*/
public static function getUidByClientId($client_id)
{
$data = static::select(array('uid'), array('client_id'=>array($client_id)));
foreach ($data as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $items) {
//$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
foreach ($items as $info) {
return $info['uid'];
}
}
}
}
/**
* 获取所有在线的群组id
*
* @return array
*/
public static function getAllGroupIdList()
{
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_GET_GROUP_ID_LIST;
$group_id_list = array();
$all_buffer_array = static::getBufferFromAllGateway($gateway_data);
foreach ($all_buffer_array as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $group_id_array) {
if (is_array($group_id_array)) {
foreach ($group_id_array as $group_id) {
if (!isset($group_id_list[$group_id])) {
$group_id_list[$group_id] = $group_id;
}
}
}
}
}
return $group_id_list;
}
/**
* 获取所有在线分组的uid数量,也就是每个分组的在线用户数
*
* @return array
*/
public static function getAllGroupUidCount()
{
$group_uid_map = static::getAllGroupUidList();
$group_uid_count_map = array();
foreach ($group_uid_map as $group_id => $uid_list) {
$group_uid_count_map[$group_id] = count($uid_list);
}
return $group_uid_count_map;
}
/**
* 获取所有分组uid在线列表
*
* @return array
*/
public static function getAllGroupUidList()
{
$data = static::select(array('uid','groups'));
$group_uid_map = array();
foreach ($data as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $items) {
//$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
foreach ($items as $connection_id => $info) {
if (empty($info['uid']) || empty($info['groups'])) {
break;
}
$uid = $info['uid'];
foreach ($info['groups'] as $group_id) {
if(!isset($group_uid_map[$group_id])) {
$group_uid_map[$group_id] = array();
}
$group_uid_map[$group_id][$uid] = $uid;
}
}
}
}
return $group_uid_map;
}
/**
* 获取所有群组在线client_id列表
*
* @return array
*/
public static function getAllGroupClientIdList()
{
$data = static::select(array('groups'));
$group_client_id_map = array();
foreach ($data as $local_ip => $buffer_array) {
foreach ($buffer_array as $local_port => $items) {
//$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
foreach ($items as $connection_id => $info) {
if (empty($info['groups'])) {
break;
}
$client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
foreach ($info['groups'] as $group_id) {
if(!isset($group_client_id_map[$group_id])) {
$group_client_id_map[$group_id] = array();
}
$group_client_id_map[$group_id][$client_id] = $client_id;
}
}
}
}
return $group_client_id_map;
}
/**
* 获取所有群组在线client_id数量,也就是获取每个群组在线连接数
*
* @return array
*/
public static function getAllGroupClientIdCount()
{
$group_client_map = static::getAllGroupClientIdList();
$group_client_count_map = array();
foreach ($group_client_map as $group_id => $client_id_list) {
$group_client_count_map[$group_id] = count($client_id_list);
}
return $group_client_count_map;
}
/**
* 根据条件到gateway搜索数据
*
* @param array $fields
* @param array $where
* @return array
*/
protected static function select($fields = array('session','uid','groups'), $where = array())
{
$t = microtime(true);
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_SELECT;
$gateway_data['ext_data'] = array('fields' => $fields, 'where' => $where);
$gateway_data_list = array();
// 有client_id,能计算出需要和哪些gateway通讯,只和必要的gateway通讯能降低系统负载
if (isset($where['client_id'])) {
$client_id_list = $where['client_id'];
unset($gateway_data['ext_data']['where']['client_id']);
$gateway_data['ext_data']['where']['connection_id'] = array();
foreach ($client_id_list as $client_id) {
$address_data = Context::clientIdToAddress($client_id);
if (!$address_data) {
continue;
}
$address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
if (!isset($gateway_data_list[$address])) {
$gateway_data_list[$address] = $gateway_data;
}
$gateway_data_list[$address]['ext_data']['where']['connection_id'][$address_data['connection_id']] = $address_data['connection_id'];
}
foreach ($gateway_data_list as $address => $item) {
$gateway_data_list[$address]['ext_data'] = json_encode($item['ext_data']);
}
// 有其它条件,则还是需要向所有gateway发送
if (count($where) !== 1) {
$gateway_data['ext_data'] = json_encode($gateway_data['ext_data']);
foreach (static::getAllGatewayAddress() as $address) {
if (!isset($gateway_data_list[$address])) {
$gateway_data_list[$address] = $gateway_data;
}
}
}
$data = static::getBufferFromSomeGateway($gateway_data_list);
} else {
$gateway_data['ext_data'] = json_encode($gateway_data['ext_data']);
$data = static::getBufferFromAllGateway($gateway_data);
}
return $data;
}
/**
* 生成验证包,用于验证此客户端的合法性
*
* @return string
*/
protected static function generateAuthBuffer()
{
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_GATEWAY_CLIENT_CONNECT;
$gateway_data['body'] = json_encode(array(
'secret_key' => static::$secretKey,
));
return GatewayProtocol::encode($gateway_data);
}
/**
* 批量向某些gateway发包,并得到返回数组
*
* @param array $gateway_data_array
* @return array
* @throws Exception
*/
protected static function getBufferFromSomeGateway($gateway_data_array)
{
$gateway_buffer_array = array();
$auth_buffer = static::$secretKey ? static::generateAuthBuffer() : '';
foreach ($gateway_data_array as $address => $gateway_data) {
if ($auth_buffer) {
$gateway_buffer_array[$address] = $auth_buffer.GatewayProtocol::encode($gateway_data);
} else {
$gateway_buffer_array[$address] = GatewayProtocol::encode($gateway_data);
}
}
return static::getBufferFromGateway($gateway_buffer_array);
}
/**
* 批量向所有 gateway 发包,并得到返回数组
*
* @param string|array $gateway_data
* @return array
* @throws Exception
*/
protected static function getBufferFromAllGateway($gateway_data)
{
$addresses = static::getAllGatewayAddress();
$gateway_buffer_array = array();
$gateway_buffer = GatewayProtocol::encode($gateway_data);
$gateway_buffer = static::$secretKey ? static::generateAuthBuffer() . $gateway_buffer : $gateway_buffer;
foreach ($addresses as $address) {
$gateway_buffer_array[$address] = $gateway_buffer;
}
return static::getBufferFromGateway($gateway_buffer_array);
}
/**
* 获取所有gateway内部通讯地址
*
* @return array
* @throws Exception
*/
protected static function getAllGatewayAddress()
{
if (isset(static::$businessWorker)) {
$addresses = static::$businessWorker->getAllGatewayAddresses();
if (empty($addresses)) {
throw new Exception('businessWorker::getAllGatewayAddresses return empty');
}
} else {
$addresses = static::getAllGatewayAddressesFromRegister();
if (empty($addresses)) {
return array();
}
}
return $addresses;
}
/**
* 批量向gateway发送并获取数据
* @param $gateway_buffer_array
* @return array
*/
protected static function getBufferFromGateway($gateway_buffer_array)
{
$client_array = $status_data = $client_address_map = $receive_buffer_array = $recv_length_array = array();
// 批量向所有gateway进程发送请求数据
foreach ($gateway_buffer_array as $address => $gateway_buffer) {
$client = stream_socket_client("tcp://$address", $errno, $errmsg, static::$connectTimeout);
if ($client && strlen($gateway_buffer) === stream_socket_sendto($client, $gateway_buffer)) {
$socket_id = (int)$client;
$client_array[$socket_id] = $client;
$client_address_map[$socket_id] = explode(':', $address);
$receive_buffer_array[$socket_id] = '';
}
}
// 超时5秒
$timeout = 5;
$time_start = microtime(true);
// 批量接收请求
while (count($client_array) > 0) {
$write = $except = array();
$read = $client_array;
if (@stream_select($read, $write, $except, $timeout)) {
foreach ($read as $client) {
$socket_id = (int)$client;
$buffer = stream_socket_recvfrom($client, 65535);
if ($buffer !== '' && $buffer !== false) {
$receive_buffer_array[$socket_id] .= $buffer;
$receive_length = strlen($receive_buffer_array[$socket_id]);
if (empty($recv_length_array[$socket_id]) && $receive_length >= 4) {
$recv_length_array[$socket_id] = current(unpack('N', $receive_buffer_array[$socket_id]));
}
if (!empty($recv_length_array[$socket_id]) && $receive_length >= $recv_length_array[$socket_id] + 4) {
unset($client_array[$socket_id]);
}
} elseif (feof($client)) {
unset($client_array[$socket_id]);
}
}
}
if (microtime(true) - $time_start > $timeout) {
break;
}
}
$format_buffer_array = array();
foreach ($receive_buffer_array as $socket_id => $buffer) {
$local_ip = ip2long($client_address_map[$socket_id][0]);
$local_port = $client_address_map[$socket_id][1];
$format_buffer_array[$local_ip][$local_port] = unserialize(substr($buffer, 4));
}
return $format_buffer_array;
}
/**
* 踢掉某个客户端,并以$message通知被踢掉客户端
*
* @param string $client_id
* @param string $message
* @return void
*/
public static function closeClient($client_id, $message = null)
{
$address_data = Context::clientIdToAddress($client_id);
if (!$address_data) {
return false;
}
$address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
return static::kickAddress($address, $address_data['connection_id'], $message);
}
/**
* 踢掉某个客户端并直接立即销毁相关连接
*
* @param string $client_id
* @return bool
*/
public static function destoryClient($client_id)
{
if ($client_id === Context::$client_id) {
return static::destoryCurrentClient();
} // 不是发给当前用户则使用存储中的地址
else {
$address_data = Context::clientIdToAddress($client_id);
if (!$address_data) {
return false;
}
$address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
return static::destroyAddress($address, $address_data['connection_id']);
}
}
/**
* 踢掉当前客户端并直接立即销毁相关连接
*
* @return bool
* @throws Exception
*/
public static function destoryCurrentClient()
{
if (!Context::$connection_id) {
throw new Exception('destoryCurrentClient can not be called in async context');
}
$address = long2ip(Context::$local_ip) . ':' . Context::$local_port;
return static::destroyAddress($address, Context::$connection_id);
}
/**
* 将 client_id 与 uid 绑定
*
* @param string $client_id
* @param int|string $uid
* @return void
*/
public static function bindUid($client_id, $uid)
{
static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_BIND_UID, '', $uid);
}
/**
* 将 client_id 与 uid 解除绑定
*
* @param string $client_id
* @param int|string $uid
* @return void
*/
public static function unbindUid($client_id, $uid)
{
static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_UNBIND_UID, '', $uid);
}
/**
* 将 client_id 加入组
*
* @param string $client_id
* @param int|string $group
* @return void
*/
public static function joinGroup($client_id, $group)
{
static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_JOIN_GROUP, '', $group);
}
/**
* 将 client_id 离开组
*
* @param string $client_id
* @param int|string $group
*
* @return void
*/
public static function leaveGroup($client_id, $group)
{
static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_LEAVE_GROUP, '', $group);
}
/**
* 取消分组
*
* @param int|string $group
*
* @return void
*/
public static function ungroup($group)
{
if (!static::isValidGroupId($group)) {
return false;
}
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_UNGROUP;
$gateway_data['ext_data'] = $group;
return static::sendToAllGateway($gateway_data);
}
/**
* 向所有 uid 发送
*
* @param int|string|array $uid
* @param string $message
*
* @return void
*/
public static function sendToUid($uid, $message)
{
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_SEND_TO_UID;
$gateway_data['body'] = $message;
if (!is_array($uid)) {
$uid = array($uid);
}
$gateway_data['ext_data'] = json_encode($uid);
static::sendToAllGateway($gateway_data);
}