-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.html
2825 lines (2261 loc) · 119 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<meta name="description" content="Swoole Cheat Sheet , Codes , function , methods of swoole extension">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="@toxmc">
<title>Swoole 4.x 速查表</title>
<meta name="description" content="Swoole 4.x LTS 速查表方便快速浏览,支持并且只支持 Swoole 4.x LTS,支持手机访问,支持中英文版本">
<meta name="keywords" content="Swoole 4.x LTS 速查表,Swoole 4.x 教程,Swoole 4.x 新手教程,Swoole 4.x Artisan,Swoole 4.x Auth,Swoole 4.x Blade,Swoole 4.x Cache,Swoole 4.x Composer,Swoole 4.x Config,Swoole 4.x Container,Swoole 4.x Cookie,Swoole 4.x DB,Swoole 4.x Environment,Swoole 4.x Event,Swoole 4.x File,Swoole 4.x Form,Swoole 4.x HTML,Swoole 4.x Helper,Swoole 4.x Input,Swoole 4.x Lang,Swoole 4.x Log,Swoole 4.x Mail,Swoole 4.x Model,Swoole 4.x Pagination,Swoole 4.x Queue,Swoole 4.x Redirect,Swoole 4.x Request,Swoole 4.x Response,Swoole 4.x Route,Swoole 4.x SSH,Swoole 4.x Schema,Swoole 4.x Security,Swoole 4.x Session,Swoole 4.x String,Swoole 4.x URL,Swoole 4.x UnitTest,Swoole 4.x Validation,Swoole 4.x View">
<link rel="stylesheet" href="assets/css/normalize.css"/>
<link rel="stylesheet" href="assets/css/foundation.min.css"/>
<link rel="stylesheet" href="assets/css/font-awesome.min.css"/>
<link rel="stylesheet" href="assets/css/page.css"/>
</head>
<body>
<div class="off-canvas-wrapper wrapper-container">
<div class="off-canvas-wrapper-inner" data-off-canvas-wrapper>
<div class="off-canvas position-left sidebar-canvas" id="offCanvasLeft" data-off-canvas data-position="left">
<button class="close-button" aria-label="Close menu" type="button" data-close>
<span aria-hidden="true">×</span>
</button>
<ul class="mobile-ofc vertical menu">
<li>
<button class="warning hollow button check-all-button">查看全部</button>
</li>
<li>
<ul class="submenu menu vertical mobile-cmd-cell" data-submenu>
</ul>
</li>
</ul>
</div>
<div class="off-canvas-content" data-off-canvas-content>
<div class="title-bar hide-for-medium">
<div class="title-bar-left">
<button class="menu-icon" type="button" data-open="offCanvasLeft"></button>
</div>
</div>
</div>
<a href="#top" id="top-button" title="Top"><i class="icon-arrow-up"></i></a>
<a href="#" class="comments-toggle" title="隐藏/展示代码注释"><i class="icon-eye-close"></i></a>
<div class="row full-width">
<div class="large-2 columns code-column sidebar">
<h5 class="sidebar-title">Swoole 4.x LTS 速查表</h6>
<hr class="horizonal-line">
<div class="show-for-medium">
<button class="warning hollow button check-all-button">查看全部</button>
<div class="clearfix"></div>
<ul class="sidebar-menu">
</ul>
<div class="clearfix"></div>
<hr class="horizonal-line">
</div>
<ul class="sidebar-bottom">
<li><a href="https://group.swoole.com/" class="button expand small radius alert">Swoole China 社区</a></li>
<li><a href="https://wiki.swoole.com/" class="button expand small radius alert">Swoole 中文文档</a></li>
<li><a href="https://www.swoole.co.uk/docs/" class="button expand small radius alert">Swoole英文文档</a></li>
<li><a href="http://compiler.swoole.com/" class="button expand small radius alert">Swoole 商业支持</a></li>
<li><a href="https://github.com/swoole/swoole-src" class="button expand small radius alert">Swoole源码GITHUB</a></li>
<li><a href="https://gitee.com/swoole/swoole" class="button expand small radius alert">Swoole源码开源中国</a></li>
<li><a href="https://group.swoole.com/home/explore/category-9" class="button expand small radius alert">Swoole 企业招聘</a></li>
<li>
<a href="" target="_blank" rel="nofollow" title="" style="display: block;margin-bottom: 23px;">
<img src="./assets/images/reward.jpeg" style="width: 180px;border: 1px solid #d8d3d3;box-shadow: 0 0 30px #d4d4d4;-moz-box-shadow: 0 0 30px #ccc;-webkit-box-shadow: 0 0 30px #d4d4d4;margin-bottom: 10px;margin-top: 21px;border-radius: 4px;">
</a>
</li>
<li>
<a href="http://weibo.com/1837553744/" target="_blank">by mc²</a>
</li>
<li class="social-icon">
<a href="http://github.com/toxmc" target="_blank" data-tooltip aria-haspopup="true" class="top" data-disable-hover="false" tabindex="2" title="此项目由 toxmc 倾情维护">
<div class="avatar"></div>
</a>
<a href="https://github.com/toxmc/swoole-cs.github.io" target="_blank" data-tooltip aria-haspopup="true" class="top" data-disable-hover="false" tabindex="2" title="在 GitHub 查看此项目">
<i class="icon-github"></i>
</a>
</li>
<li class="languages-flag">
<a href="./index.html"><i class="cn flag"></i></a>
<span class="vertical-line">|</span>
<a href="./index_en-US.html"><i class="gb flag"></i></a>
</li>
</ul>
</div>
<div class="large-10 columns code-column code-container">
<div class="grid">
<section class="cmd-description grid-item">
<h4><a name="Server_Function" href="#Server_Function">Server 函数列表</a> <a href="https://wiki.swoole.com/wiki/page/15.html" title="Server Function Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// 创建一个异步Server对象。
$serv = new swoole_server('0.0.0.0', '9501', $mode = SWOOLE_PROCESS, $sock_type = SWOOLE_SOCK_TCP);
// swoole_server->set函数用于设置swoole_server运行时的各项参数。
// 服务器启动后通过$serv->setting来访问set函数设置的参数数组。
$serv->set(array(
'reactor_num' => 2,
'worker_num' => 4,
'backlog' => 128,
'max_request' => 50,
'dispatch_mode' => 1,
));
// 注册Server的事件回调函数。
$serv->on('connect', function ($serv, $fd){
echo "Client:Connect.\n";
});
// 增加监听的端口。业务代码中可以通过调用swoole_server::connection_info来获取某个连接来自于哪个端口。
$serv->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP);
// 监听一个新的Server端口,此方法是addlistener的别名
$serv->listen("127.0.0.1", 9503, SWOOLE_SOCK_TCP);
// 添加一个用户自定义的工作进程。此函数通常用于创建一个特殊的工作进程,用于监控、上报或者其他特殊的任务。
$process = new swoole_process(function($process) use ($server) {
while (true) {
$msg = $process->read();
foreach($server->connections as $conn) {
$server->send($conn, $msg);
}
}
});
$server->addProcess($process);
// 启动server,监听所有TCP/UDP端口
$serv->start();
// 重启所有worker进程。$only_reload_taskworkrer 是否仅重启task进程
$serv->reload($only_reload_taskworkrer = false);
// 使当前worker进程停止运行,并立即触发onWorkerStop回调函数。
swoole_server->stop(int $worker_id = -1, bool $waitEvent = false);
// 此函数可以用在worker进程内。向主进程发送SIGTERM也可以实现关闭服务器。
$serv->shutdown();
// tick定时器,可以自定义回调函数。此函数是swoole_timer_tick的别名。
$serv->tick(1000, function ($id) {
var_dump($id);
});
// 在指定的时间后执行函数,swoole_server::after函数是一个一次性定时器,执行完成后就会销毁
$serv->after(2000, function(){
echo "Timeout: ".microtime(true)."\n";
});
// 延后执行一个PHP函数。Swoole底层会在EventLoop循环完成后执行此函数。
// 此函数的目的是为了让一些PHP代码延后执行,程序优先处理IO事件。
$server->defer(function() use ($db) {
$db->close();
});
// 清除tick/after定时器,此函数是 swoole_timer_clear 的别名。
$timer_id = $server->tick(1000, function ($id) use ($server) {
$server->clearTimer($id);
});
// 关闭客户端连接,操作成功返回true,失败返回false.
$serv->close($fd);
// 向客户端发送数据 $data,发送的数据,TCP协议最大不得超过2M,可修改 buffer_output_size 改变允许发送的最大包长度
// UDP协议不得超过65507,UDP包头占8字节, IP包头占20字节,65535-28 = 65507
$serv->send($fd, 'Swoole: '.$data);
// 发送文件到TCP客户端连接
$serv->sendfile($fd, __DIR__.'/test.jpg');
// 向任意的客户端IP:PORT发送UDP数据包
$serv->sendto("127.0.0.1", 9999, "hello world");
// 阻塞地向客户端发送数据
server->sendwait($fd, "hello world");
// 此函数可以向任意worker进程或者task进程发送消息。在非主进程和管理进程中可调用。收到消息的进程会触发onPipeMessage事件
$serv->sendMessage("hello task process", $worker_id);
// 检测fd对应的连接是否存在,$fd对应的TCP连接存在返回true,不存在返回false
$serv->exist($fd)
// 停止接收数据。调用此函数后会将连接从EventLoop中移除,不再接收客户端数据
$serv->pause($fd)
// 恢复数据接收。与pause方法成对使用,调用此函数后会将连接重新加入到EventLoop中,继续接收客户端数据
$serv->resume(int $fd);
// swoole_server->getClientInfo函数用来获取连接的信息,别名是swoole_server->connection_info
$fdinfo = $serv->connection_info($fd);
// 用来遍历当前Server所有的客户端连接,方法是基于共享内存的,不存在IOWait
// 推荐使用 swoole_server::$connections 迭代器来遍历连接,getClientList的别名是connection_list
$conn_list = $serv->getClientList($start_fd, 10);
// 将连接绑定一个用户定义的UID,可以设置dispatch_mode=5设置以此值进行hash固定分配。
// 可以保证某一个UID的连接全部会分配到同一个Worker进程。
$serv->bind($fd, $uid)
// 得到当前Server的活动TCP连接数,启动时间,accpet/close的总次数等信息。
$serv_stats = $serv->stats();
// 投递一个异步任务到task_worker池中。此函数是非阻塞的,执行完毕会立即返回。Worker进程可以继续处理新的请求。
// 使用Task功能,必须先设置 task_worker_num,并且必须设置Server的onTask和onFinish事件回调函数
$task_id = $serv->task("some data");
// taskwait与task方法作用相同,用于投递一个异步的任务到task进程池去执行。
// 与task不同的是taskwait是同步等待的,直到任务完成或者超时返回。
$serv->taskwait(['type' => 'array', 'value' => $data]);
// 并发执行多个Task,$tasks 必须为数字索引数组,不支持关联索引数组
$tasks[] = mt_rand(1000, 9999); // 任务1
$tasks[] = mt_rand(1000, 9999); // 任务2
var_dump($tasks);
// 等待所有Task结果返回,超时为10s
$results = $serv->taskWaitMulti($tasks, 10.0);
// 并发执行Task并进行协程调度
$result = $serv->taskCo($tasks, 0.5);
// 此函数用于在task进程中通知worker进程,投递的任务已完成。此函数可以传递结果数据给worker进程。
$serv->finish("response");
// 检测服务器所有连接,并找出已经超过约定时间的连接。
// 如果指定if_close_connection,则自动关闭超时的连接。未指定仅返回连接的fd数组。
$closeFdArr = $serv->heartbeat();
// 获取最近一次操作错误的错误码。业务代码中可以根据错误码类型执行不同的逻辑。
$errCode = $serv->getLastError();
// 调用此方法可以得到底层的socket句柄,返回的对象为sockets资源句柄。
// 依赖PHP的sockets扩展,并且编译swoole时需要开启--enable-sockets选项
$socket = $serv->getSocket();
// 设置客户端连接为保护状态,不被心跳线程切断。
$serv->protect(int $fd, bool $value = 1);
// 确认连接,与enable_delay_receive或wait_for_bind配合使用。当客户端建立连接后,并不监听可读事件。
// 仅触发onConnect事件回调在onConnect回调中执行confirm确认连接,这时服务器才会监听可读事件,接收来自客户端连接的数据。
$serv->confirm(int $fd);
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="Server_attribute" href="#Server_attribute">Server 属性列表</a> <a href="https://wiki.swoole.com/wiki/page/243.html" title="Server Attribute Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// swoole_server::set()函数所设置的参数会保存到swoole_server::$setting属性上。在回调函数中可以访问运行参数的值。
echo $serv->setting['worker_num'];
// 返回当前服务器主进程的PID。
int $serv->master_pid;
// 返回当前服务器管理进程的PID。
int $serv->manager_pid;
// 得到当前Worker进程的编号,包括Task进程。Worker进程编号范围是[0, worker_num]
// Task进程编号范围是[worker_num, worker_num + task_worker_num]
int $serv->worker_id;
// 得到当前Worker进程的操作系统进程ID。与posix_getpid()的返回值相同。
int $serv->worker_pid;
// 布尔类型,true表示当前的进程是Task工作进程,false表示当前的进程是Worker进程
bool $serv->taskworker;
// TCP连接迭代器,可以使用foreach遍历服务器当前所有的连接,
// 此属性的功能与swoole_server->connnection_list是一致的,但是更加友好。遍历的元素为单个连接的fd。
// 监听端口数组,如果服务器监听了多个端口可以遍历swoole_server::$ports得到所有Swoole\Server\Port对象。
// 其中swoole_server::$ports[0]为构造方法所设置的主服务器端口。
$ports = swoole_server::$ports;
$ports[0]->set($settings);
$ports[1]->on("Receive", function(){});
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="ServerConfig" href="#ServerConfig">Server 配置选项</a> <a href="https://wiki.swoole.com/wiki/page/274.html" title="Server Config @ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
$serv->set(array(
// 通过此参数来调节主进程内事件处理线程的数量,以充分利用多核。默认会启用CPU核数相同的数量。一般设置为CPU核数的1-4倍
'reactor_num' => 2,
// 设置启动的Worker进程数。业务代码是全异步非阻塞的,这里设置为CPU的1-4倍最合理
// 业务代码为同步阻塞,需要根据请求响应时间和系统负载来调整
'worker_num' => 2,
// 设置worker进程的最大任务数,默认为0,一个worker进程在处理完超过此数值的任务后将自动退出,进程退出后会释放所有内存和资源。
'max_request' => 1000,
// 服务器程序,最大允许的连接数, 此参数用来设置Server最大允许维持多少个TCP连接。超过此数量后,新进入的连接将被拒绝
'max_connection' => 10000,
// 配置Task进程的数量,配置此参数后将会启用task功能。所以Server务必要注册onTask
'task_worker_num' => 2,
// 设置Task进程与Worker进程之间通信的方式。1使用unix socket通信,默认模式, 2使用消息队列通信, 3使用消息队列通信,并设置为争抢模式
'task_ipc_mode' => 1
// 设置task进程的最大任务数。一个task进程在处理完超过此数值的任务后将自动退出。
'task_max_request' => 0,
// 设置task的数据临时目录,在swoole_server中,如果投递的数据超过8192字节,将启用临时文件来保存数据
'task_tmpdir' => '/tmp',
// 数据包分发策略默认为2。1轮循模式,2固定模式,3抢占模式,4IP分配,5UID分配
'dispatch_mode' => 2,
// 设置dispatch函数,swoole底层了内置了5种dispatch_mode,如果仍然无法满足需求。
// 可以使用编写C++函数或PHP函数,实现dispatch逻辑。使用方法:
'dispatch_func' => 'my_dispatch_function',
// 设置消息队列的KEY,仅在task_ipc_mode = 2/3时使用。
// 设置的Key仅作为Task任务队列的KEY,此参数的默认值为ftok($php_script_file, 1)
'message_queue_key' => ftok(SYS_ROOT . 'queue.msg', 1),
// 设置守护进程模式
'daemonize' => 1,
// Listen队列长度,如backlog => 128,此参数将决定最多同时有多少个等待accept的连接
'backlog' => 128,
// 指定swoole错误日志文件。在swoole运行期发生的异常信息会记录到这个文件中。默认会打印到屏幕
'log_file' => '/data/logs/swoole.log',
// 设置swoole_server错误日志打印的等级,范围是0-5。低于log_level设置的日志信息不会抛出
'log_level' => 1,
// 启用心跳检测,此选项表示每隔多久轮循一次,单位为秒
'heartbeat_check_interval' => 10,
// 与heartbeat_check_interval配合使用。表示连接最大允许空闲的时间
'heartbeat_idle_time' => 20,
// 打开EOF检测,此选项将检测客户端连接发来的数据,当数据包结尾是指定的字符串时才会投递给Worker进程
// 否则会一直拼接数据包,直到超过缓存区或者超时才会中止。当出错时底层会认为是恶意连接,丢弃数据并强制关闭连接
'open_eof_check' => true,
// 启用EOF自动分包。当设置open_eof_check后,底层检测数据是否以特定的字符串结尾来进行数据缓冲
'open_eof_split' => true,
// 与 open_eof_check 或者 open_eof_split 配合使用,设置EOF字符串。
'package_eof' => "\r\r\n",
// 打开包长检测特性。包长检测提供了固定包头+包体这种格式协议的解析。
// 启用后,可以保证Worker进程onReceive每次都会收到一个完整的数据包。
'open_length_check' => true,
// 长度值的类型,接受一个字符参数,与php的 pack 函数一致。
'package_length_type' => 'N',
// 设置长度解析函数,支持C++或PHP的2种类型的函数。长度函数必须返回一个整数
'package_length_func' => 'package_length_func_name'
// 设置最大数据包尺寸,单位为字节
'package_max_length' => 2000000,
// 启用CPU亲和性设置
'open_cpu_affinity' => 1,
// cpu_affinity_ignore 设置将此CPU空出,专门用于处理网络中断
'cpu_affinity_ignore' => [0,1],
// 启用open_tcp_nodelay,开启后TCP连接发送数据时会关闭Nagle合并算法,立即发往客户端连接
'open_tcp_nodelay' => 1,
// 启用tcp_defer_accept特性,可以设置为一个数值,表示当一个TCP连接有数据发送时才触发accept
'tcp_defer_accept' => 5
// 设置SSL隧道加密,设置值为一个文件名字符串,制定cert证书和key私钥的路径
'ssl_cert_file' => __DIR__.'/config/ssl.crt',
'ssl_key_file' => __DIR__.'/config/ssl.key',
// 设置OpenSSL隧道加密的算法。Server与Client使用的算法必须一致,否则SSL/TLS握手会失败,连接会被切断
'ssl_method' => SWOOLE_SSLv3_CLIENT_METHOD,
// 启用SSL后,设置ssl_ciphers来改变openssl默认的加密算法
'ssl_ciphers' => 'ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP',
// 设置worker/task子进程的所属用户
'user' => 'swoole',
// 设置worker/task子进程的进程用户组
'group' => 'www-data',
// 重定向Worker进程的文件系统根目录
'chroot' => '/data/server/',
// 在Server启动时自动将master进程的PID写入到文件,在Server关闭时自动删除PID文件
'pid_file' => __DIR__.'/server.pid',
// 调整管道通信的内存缓存区长度。Swoole使用Unix Socket实现进程间通信。
'pipe_buffer_size' => 32 * 1024 *1024,
// 配置发送输出缓存区内存尺寸
'buffer_output_size' => 32 * 1024 *1024
// 配置客户端连接的缓存区长度
'socket_buffer_size' => 128 * 1024 *1024
// swoole在配置dispatch_mode=1或3后,因为系统无法保证onConnect/onReceive/onClose的顺序,默认关闭了onConnect/onClose事件。
// 如果应用程序需要onConnect/onClose事件,并且能接受顺序问题可能带来的安全风险,
// 可以通过设置enable_unsafe_event为true,启用onConnect/onClose事件
'enable_unsafe_event' => true,
// swoole在配置dispatch_mode=1或3后,系统无法保证onConnect/onReceive/onClose的顺序,因此可能会有一些请求数据在连接关闭后,
// 才能到达Worker进程。discard_timeout_request配置默认为true,表示如果worker进程收到了已关闭连接的数据请求,将自动丢弃。
// discard_timeout_request如果设置为false,表示无论连接是否关闭Worker进程都会处理数据请求。
'discard_timeout_request' => true,
// 设置端口重用
'enable_reuse_port' => true,
// 设置此选项为true后,accept客户端连接后将不会自动加入EventLoop,仅触发onConnect回调。
// worker进程可以调用$serv->confirm($fd)对连接进行确认,此时才会将fd加入EventLoop开始进行数据收发,
// 也可以调用$serv->close($fd)关闭此连接。
'enable_delay_receive' => true,
// 启用Http协议处理
'open_http_protocol' => true,
// 启用HTTP2协议解析,需要依赖--enable-http2编译选项。默认为false
'open_http2_protocol' => true,
// 启用websocket协议处理,Swoole\WebSocket\Server会自动启用此选项
'open_websocket_protocol' => true,
// 启用mqtt协议处理,启用后会解析mqtt包头,worker进程onReceive每次会返回一个完整的mqtt数据包
'open_mqtt_protocol' => true,
// 设置异步重启开关
'reload_async' => true,
// 开启TCP快速握手特性。此项特性,可以提升TCP短连接的响应速度,在客户端完成握手的第三步,发送SYN包时携带数据
'tcp_fastopen' => true
// 开启请求慢日志。启用后Manager进程会设置一个时钟信号,定时侦测所有Task和Worker进程,
// 一旦进程阻塞导致请求超过规定的时间,将自动打印进程的PHP函数调用栈
'request_slowlog_file' => '/tmp/trace.log',
// enable_coroutine参数,默认为true,通过设置为false可关闭内置协程
'enable_coroutine' => false
// 设置当前工作进程最大协程数量,超过max_coroutine底层将无法创建新的协程,底层会抛出错误,并直接关闭连接
'max_coroutine' => 3000,
));
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="constant" href="#app">预定义常量</a> <a href="https://wiki.swoole.com/wiki/page/26.html" title="Server constant @ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-js">
// 预定义常量
SWOOLE_VERSION 当前Swoole的版本号,字符串类型,如1.6.0
// swoole_server构造函数参数
SWOOLE_BASE 使用Base模式,业务代码在Reactor进程中直接执行
SWOOLE_PROCESS 使用进程模式,业务代码在Worker进程中执行
// swoole_client构造函数参数
SWOOLE_SOCK_TCP 创建tcp socket
SWOOLE_SOCK_TCP6 创建tcp ipv6 socket
SWOOLE_SOCK_UDP 创建udp socket
SWOOLE_SOCK_UDP6 创建udp ipv6 socket
SWOOLE_SOCK_SYNC 同步客户端
SWOOLE_SOCK_ASYNC 异步客户端
// swoole_lock构造函数参数
SWOOLE_FILELOCK 创建文件锁
SWOOLE_MUTEX 创建互斥锁
SWOOLE_RWLOCK 创建读写锁
SWOOLE_SPINLOCK 创建自旋锁
SWOOLE_SEM 创建信号量
// SSL加密方法
SWOOLE_SSLv3_SERVER_METHOD;
SWOOLE_SSLv3_METHOD;
SWOOLE_SSLv3_CLIENT_METHOD;
SWOOLE_SSLv23_METHOD 默认加密方法;
SWOOLE_SSLv23_SERVER_METHOD;
SWOOLE_SSLv23_CLIENT_METHOD;
SWOOLE_TLSv1_METHOD;
SWOOLE_TLSv1_SERVER_METHOD;
SWOOLE_TLSv1_CLIENT_METHOD;
SWOOLE_TLSv1_1_METHOD;
SWOOLE_TLSv1_1_SERVER_METHOD;
SWOOLE_TLSv1_1_CLIENT_METHOD;
SWOOLE_TLSv1_2_METHOD;
SWOOLE_TLSv1_2_SERVER_METHOD;
SWOOLE_TLSv1_2_CLIENT_METHOD;
SWOOLE_DTLSv1_METHOD;
SWOOLE_DTLSv1_SERVER_METHOD;
SWOOLE_DTLSv1_CLIENT_METHOD;
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="event" href="#event">事件回调函数</a> <a href="https:// wiki.swoole.com/wiki/page/41.html" title="event function@ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// Server启动在主进程的主线程回调此函数
$serv->on('Start', function(Swoole\Server $server){});
// 此事件在Server正常结束时发生
$serv->on('Shutdown', function(Swoole\Server $server){});
// 此事件在Worker进程/Task进程启动时发生
$serv->on('WorkerStart', function(Swoole\Server $server, int $worker_id){});
// 此事件在worker进程终止时发生
$serv->on('WorkerStop', function(Swoole\Server $server, int $worker_id){});
// 仅在开启reload_async特性后有效会先创建新的Worker进程处理新请求,旧的Worker进程自行退出。
$serv->on('WorkerExit', function(Swoole\Server $server, int $worker_id){});
// 有新的连接进入时,在worker进程中回调
$serv->on('Connect', function(Swoole\Server $server, int $fd, int $reactorId){});
// 接收到数据时回调此函数,发生在worker进程中
$serv->on('Receive', function(Swoole\Server $server, int $fd, int $reactor_id, string $data){});
// 接收到UDP数据包时回调此函数,发生在worker进程中
$serv->on('Packet', function(Swoole\Server $server, string $data, array $client_info){});
// TCP客户端连接关闭后,在worker进程中回调此函数
$serv->on('Close', function(Swoole\Server $server, int $fd, int $reactorId){});
// 当缓存区达到最高水位时触发此事件。
$serv->on('BufferFull', function(Swoole\Server $serv, int $fd){});
// 当缓存区低于最低水位线时触发此事件
$serv->on('BufferEmpty', function(Swoole\Server $serv, int $fd){});
// 在task_worker进程内被调用。worker进程可以使用swoole_server_task函数向task_worker进程投递新的任务。
// 当前的Task进程在调用onTask回调函数时会将进程状态切换为忙碌,这时将不再接收新的Task,
// 当onTask函数返回时会将进程状态切换为空闲然后继续接收新的Task。
$serv->on('Task', function(Swoole\Server $serv, int $task_id, int $src_worker_id, mixed $data){});
// 当worker进程投递的任务在task_worker中完成时,
// task进程会通过swoole_server->finish()方法将任务处理的结果发送给worker进程
$serv->on('Finish', function(Swoole\Server $serv, int $task_id, string $data){});
// 当工作进程收到由 sendMessage 发送的管道消息时会触发onPipeMessage事件。worker/task进程都可能会触发onPipeMessage事件
$serv->on('PipeMessage', function(Swoole\Server $server, int $src_worker_id, mixed $message){});
// 当worker/task_worker进程发生异常后会在Manager进程内回调此函数
$serv->on('WorkerError', function(Swoole\Server $serv, int $worker_id, int $worker_pid, int $exit_code, int $signal){});
// 当管理进程启动时调用它
$serv->on('ManagerStart', function(Swoole\Server $serv){});
// 当管理进程结束时调用它
$serv->on('ManagerStop', function(Swoole\Server $serv){});
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="Client_function" href="#Client_function">Client 方法列表</a> <a href="https://wiki.swoole.com/wiki/page/27.html" title="Client function list @ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// 创建一个client客户端对象
$cli = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
// 设置客户端参数,必须在connect前执行
$client->set([
'package_eof' => "\r\n\r\n",
]);
// 注册异步事件回调函数。参数1为事件类型,支持connect/error/receive/close 4种
// 参数2为回调函数,可以是函数名字符串、匿名函数、类静态方法、对象方法。
$client->on("connect", function($cli) {
$cli->send("hello world\n");
});
// 连接到远程服务器
$cli->connect('127.0.0.1', 9501, float $timeout = 0.5, int $flag = 0)
// 返回swoole_client的连接状态,返回false,表示当前未连接到服务器。返回true,表示当前已连接到服务器
$cli->isConnected();
// 调用此方法可以得到底层的socket句柄,返回的对象为sockets资源句柄
$socket = $client->getSocket();
// 用于获取客户端socket的本地host:port,必须在连接之后才可以使用
$socketName = $client->getsockname();
// 获取对端socket的IP地址和端口,仅支持SWOOLE_SOCK_UDP/SWOOLE_SOCK_UDP6类型的swoole_client对象
var_dump($client->getpeername());
// 获取服务器端证书信息,执行成功返回一个X509证书字符串信息,执行失败返回false
var_dump($client->getPeerCert());
// 发送数据到远程服务器,必须在建立连接后,才可向Server发送数据
$client->send($data);
// 向任意IP:PORT的主机发送UDP数据包,仅支持SWOOLE_SOCK_UDP/SWOOLE_SOCK_UDP6类型的swoole_client对象
$client->sendto('::1', 9502, "admin2");
// 发送文件到服务器,本函数是基于sendfile操作系统调用实现
$cli->sendfile(__DIR__.'/test.txt');
// recv方法用于从服务器端接收数据,$size 接收数据的缓存区最大长度,$flags可以接收一些特殊的SOCKET接收设置
$cli->recv($size=65535, $flags=0)
// 关闭连接,操作成功返回 true
$cli->close();
// swoole_client->sleep()调用此方法会从事件循环中移除当前socket的可读监听,停止接收数据
// 此方法仅停止从socket中接收数据,但不会移除可写事件,所以不会影响发送队列
// swoole_client->wakeup()调用此方法会重新监听可读事件,将socket连接从睡眠中唤醒,
// 如果socket并未进入sleep模式,wakeup操作没有任何作用
$client->on("receive", function(swoole_client $cli, $data){
$cli->sleep();
swoole_timer_after(5000, function() use ($cli) {
$cli->wakeup();
});
});
// 动态开启SSL隧道加密
$client->enableSSL()
// swoole_client的并行处理中用了select来做IO事件循环
int swoole_client_select(array &$read, array &$write, array &$error, float $timeout);
$clients = array();
for($i=0; $i< 20; $i++){
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC); // 同步阻塞
$ret = $client->connect('127.0.0.1', 9501, 0.5, 0);
if (!$ret) {
echo "Connect Server fail.errCode=".$client->errCode;
} else {
$client->send("HELLO WORLD\n");
$clients[$client->sock] = $client;
}
}
while (!empty($clients)) {
$write = $error = array();
$read = array_values($clients);
$n = swoole_client_select($read, $write, $error, 0.6);
if ($n > 0) {
foreach ($read as $index => $c) {
echo "Recv #{$c->sock}: " . $c->recv() . "\n";
unset($clients[$c->sock]);
}
}
}
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="Client_event" href="#events">Client 回调函数</a> <a href="https://wiki.swoole.com/wiki/page/459.html" title="Client Events @ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// 客户端连接服务器成功后会回调此函数
$client->on("connect", function(swoole_client $cli) {});
// 连接服务器失败时会回调此函数。
$client->on("error", function(swoole_client $cli){});
// 客户端收到来自于服务器端的数据时会回调此函数
$client->on("receive", function(swoole_client $cli, $data){});
// 连接被关闭时回调此函数
$client->on("close", function(swoole_client $cli){});
// 当缓存区达到最高水位时触发此事件,设置client->buffer_high_watermark选项来控制缓存区高水位线
$client->on("bufferFull", function(swoole_client $cli){});
// 当缓存区低于最低水位线时触发此事件,设置client->buffer_low_watermark来控制缓存区低水位线
$client->on("bufferEmpty", function(swoole_client $cli){});
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="Client_attribute" href="#Client_attribute">Client 属性列表</a> <a href="https://wiki.swoole.com/wiki/page/34.html" title="Client attribute @ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// 类型为int型。当connect/send/recv/close失败时,会自动设置$swoole_client->errCode的值。
// errCode的值等于Linux errno。可使用socket_strerror将错误码转为错误信息。
$client->errCode
echo socket_strerror($client->errCode);
// 类型为int。sock属性是此socket的文件描述符
// $client->sock属性值,仅在$client->connect后才能取到。在未连接服务器之前,此属性的值为null
$client->sock
$sock = fopen("php://fd/".$swoole_client->sock);
// 类型: boolean,表示此连接是新创建的还是复用已存在的。与SWOOLE_KEEP配合使用。
// WebSocket客户端与服务器建立连接后需要进行握手,如果连接是复用的,那就不需要再次进行握手,直接发送WebSocket数据帧即可。
$client->reuse
if ($client->reuse) {
$client->send($data);
} else {
$client->doHandShake();
$client->send($data);
}
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="Client_constant" href="#Client_constant">Client 常量</a> <a href="https://wiki.swoole.com/wiki/page/504.html" title="Client constant @ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<h6>基础使用</h6>
<pre class="prettyprint lang-php">
$client->recv(8192, swoole_client::MSG_PEEK | swoole_client::MSG_DONTWAIT);
// 用于swoole_client->recv方法的第二个参数,阻塞等待直到收到指定长度的数据后返回。
swoole_client::MSG_WAITALL
// 非阻塞接收数据,无论是否有数据都会立即返回。
swoole_client::MSG_DONTWAIT
// 窥视socket缓存区中的数据。设置MSG_PEEK参数后,recv读取数据不会修改指针,
// 因此下一次调用recv仍然会从上一次的位置起返回数据。
swoole_client::MSG_PEEK
// 读取带外数据。
swoole_client::MSG_OOB
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="Client_config" href="#Client_config">Client 配置选项</a> <a href="https://wiki.swoole.com/wiki/page/p-client_setting.html" title="Pagination @ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// Swoole\Client和Swoole\Http\Client可以使用set方法设置一些选项,启用某些特性。
// 结束符检测
$client->set(array(
'open_eof_check' => true,
'package_eof' => "\r\n\r\n",
'package_max_length' => 1024 * 1024 * 2,
))
// 长度检测
$client->set(array(
'open_length_check' => 1,
'package_length_type' => 'N',
'package_length_offset' => 0,
'package_body_offset' => 4,
'package_max_length' => 2000000,
));
// MQTT协议
// 启用MQTT协议解析,onReceive回调将收到完整的MQTT数据包。
$client->set(array(
'open_mqtt_protocol' => true,
));
// Socket缓存区尺寸
// 包括socket底层操作系统缓存区、应用层接收数据内存缓存区、应用层发送数据内存缓冲区
$client->set(array(
'socket_buffer_size' => 1024*1024*2,
));
// 关闭Nagle合并算法
$client->set(array(
'open_tcp_nodelay' => true,
));
// SSL/TLS证书
// swoole-1.7.21或更高版本可用
$client->set(array(
'ssl_cert_file' => $your_ssl_cert_file_path,
'ssl_key_file' => $your_ssl_key_file_path,
));
// 绑定IP和端口,机器有多个网卡的情况下,设置bind_address参数可以强制客户端Socket绑定某个网络地址。
// 设置bind_port可以使客户端Socket使用固定的端口连接到外网服务器
// swoole-1.8.5或更高版本可用
$client->set(array(
'bind_address' => '192.168.1.100',
'bind_port' => 36002,
));
// Socks5代理设置
// socks5_username、socks5_password为可选参数
$client->set(array(
'socks5_host' => '192.168.1.100',
'socks5_port' => 1080,
'socks5_username' => 'username',
'socks5_password' => 'password',
));
// Http代理设置
$client->set(array(
'http_proxy_host' => '192.168.1.100',
'http_proxy_port' => 1080,
));
// ssl_verify_peer验证服务器端证书。
// 启用后会验证证书和主机域名是否对应,如果为否将自动关闭连接
$client->set([
'ssl_verify_peer' => true,
])
// 自签名证书
// 可设置ssl_allow_self_signed为true,允许自签名证书。
$client->set([
'ssl_verify_peer' => true,
'ssl_allow_self_signed' => true,
])
// ssl_host_name 设置服务器主机名称,与ssl_verify_peer配置或Client::verifyPeerCert配合使用。
$client->set([
'ssl_host_name' => 'www.google.com',
])
// ssl_cafile 当设置ssl_verify_peer为true时, 用来验证远端证书所用到的CA证书。
// 本选项值为CA证书在本地文件系统的全路径及文件名。
$client->set([
'ssl_cafile' => '/etc/CA',
])
// ssl_capath 如果未设置ssl_cafile,或者ssl_cafile所指的文件不存在时,
// 会在ssl_capath所指定的目录搜索适用的证书。 该目录必须是已经经过哈希处理的证书目录。
$client->set([
'ssl_capath' => '/etc/capath/',
])
// package_length_func 设置长度计算函数,与Server的使用方法完全一致
$client->set(array(
'open_length_check' => true,
'package_length_func' => function ($data) {
if (strlen($data) < 8) {
return 0;
}
$length = intval(trim(substr($data, 0, 8)));
if ($length <= 0) {
return -1;
}
return $length + 8;
},
));
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="Coroutine" href="#Coroutine">Coroutine</a> <a href="https://wiki.swoole.com/wiki/page/752.html" title="Coroutine @ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// 协程设置
Swoole\Coroutine::set([
// 设置最大协程数,超过限制后底层将无法创建新的协程
'max_coroutine' => 4096,
// 设置单个协程初始栈的内存尺寸,默认为8192
'stack_size' => 8192
]);
// 短名称
// 在2.0.13与2.1.0或更高版本中,增加了协程短名特性,简化了协程相关API的名称书写。
// 可修改php.ini设置swoole.use_shortname来关闭/开启短名,默认为开启。
// 创建协程
go(function () {
co::sleep(0.5);
echo "hello";
});
go("test");
go([$object, "method"]);
// 通道操作
$c = new chan(1);
$c->push($data);
$c->pop();
// 协程客户端
$redis = new Co\Redis;
$mysql = new Co\MySQL;
$http = new Co\Http\Client;
$tcp = new Co\Client;
$http2 = new Co\Http2\Client;
// 其他 API
co::sleep(100);
co::fread($fp);
co::gethostbyname('www.baidu.com');
// 获取当前协程的唯一ID 仅在当前进程内唯一,成功时返回当前协程ID(int), 如果当前不在协程环境中,则返回-1
echo Swoole\Coroutine::getuid();
// 创建一个新的协程,并立即执行,创建成功返回true,失败返回false
// 在2.1.0或更高版本中如果开启了swoole.use_shortname,可以直接使用go关键词创建新的协程
function Swoole\Coroutine::create(callable $function);
// 恢复某个协程,使其继续运行
function Swoole\Coroutine::resume(string $coroutineId);
// 挂起当前协程
function Swoole\Coroutine::suspend();
// 协程方式读取文件。
function Coroutine::fread(resource $handle, int $length = 0);
// 协程方式按行读取文件内容
function Coroutine::fgets(resource $handle);
// 协程方式向文件写入数据
function Coroutine::fwrite(resource $handle, string $data, int $length = 0);
// 进入等待状态
function Coroutine::sleep(float $seconds);
// 将域名解析为IP,基于同步的线程池模拟实现。底层自动进行协程调度
function Coroutine::gethostbyname(string $domain, int $family = AF_INET): string | bool
// 进行DNS解析,查询域名对应的IP地址,与gethostbyname不同,getaddrinfo支持更多参数设置,而且会返回多个IP结果。
function Coroutine::getaddrinfo(string $domain, int $family = AF_INET, int $socktype = SOCK_STREAM,
int $protocol = IPPROTO_TCP, string $service = null): array | bool
$array = co::getaddrinfo("www.baidu.com");
// 执行一条shell指令。底层自动进行协程调度。
function Coroutine::exec(string $cmd) : array;
// 协程方式读取文件
function Coroutine::readFile(string $filename);
// 协程方式写入文件
function Coroutine::writeFile(string $filename, string $fileContent, int $flags);
// 获取协程状态
function \Swoole\Coroutine::stats() : array
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="Coroutine_Channel" href="#Coroutine_Channel">Coroutine\Channel</a> <a href="https://wiki.swoole.com/wiki/page/p-coroutine_channel.html" title="Filesystem @ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<pre class="prettyprint lang-php">
// 通道构造方法
Coroutine\Channel->__construct(int $capacity = 0)
// 向通道中写入数据
function Coroutine\Channel->push(mixed $data) : bool;
// 从通道中读取数据
function Coroutine\Channel->pop(float $timeout = 0) : mixed;
// 获取通道的状态
function Coroutine\Channel->stats() : array;
// 关闭通道。并唤醒所有等待读写的协程
funtion Coroutine\Channel->close();
// 通道读写检测。类似于socket_select和stream_select可以检测channel是否可进行读写
// $read 数组引用类型,元素为channel对象,读操作检测,可以为null
// $write 数组引用类型,元素为channel对象,写操作检测,可以为null
// $timeout 浮点型,超时设置,单位为秒,最小粒度为0.001秒,即1ms。默认为0,表示永不超时
function Coroutine\Channel::select(array &$read, array &$write, float $timeout = 0);
// 获取通道中的元素数量
public function length(): int
// 判断当前通道是否为空
public function isEmpty(): bool
// 判断当前通道是否已满
public function isFull(): bool
// 构造函数中设定的容量会保存在此,不过如果设定的容量小于1则此变量会等于1
Coroutine\Channel->$capacity
// 协程通道错误code
Coroutine\Channel->$errCode
</pre>
</section>
<section class="cmd-description grid-item">
<h4><a name="Coroutine_Client" href="#Coroutine_Client">Coroutine\Client</a> <a href="https://wiki.swoole.com/wiki/page/p-coroutine_client.html" title="Coroutine Client @ Swoole Docs"><i class="icon-file-text"></i></a></h4>
<h6>Install and run</h6>
<pre class="prettyprint lang-php">
// 提供了TCP和UDP传输协议Socket客户端的封装代码,使用时仅需new Swoole\Coroutine\Client即可。
$client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);