1+ <?php
2+ namespace cathy \AsyncTask \command ;
3+ use think \console \Command ;
4+ use think \console \Input ;
5+ use think \console \input \Argument ;
6+ use think \console \Output ;
7+ use think \facade \Config ;
8+ use Workerman \Worker ;
9+
10+ class WebsocketService extends Command
11+ {
12+ protected $ lastMtime ;
13+
14+ public function configure ()
15+ {
16+ $ this ->setName ('worker:websocket ' )
17+ ->addArgument ('action ' , Argument::OPTIONAL , "start|stop|restart|reload|status|connections " , 'start ' )
18+ ->setDescription ('Websocket Server for ThinkPHP6 ' );
19+ }
20+
21+ public function execute (Input $ input , Output $ output )
22+ {
23+ $ configs = include_once __DIR__ .'/../config/websocket.php ' ;
24+ $ action = $ input ->getArgument ('action ' );
25+
26+ if (DIRECTORY_SEPARATOR !== '\\' ) {
27+ if (!in_array ($ action , ['start ' , 'stop ' , 'reload ' , 'restart ' , 'status ' , 'connections ' ])) {
28+ $ output ->writeln ("Invalid argument action: {$ action }, Expected start|stop|restart|reload|status|connections . " );
29+ exit (1 );
30+ }
31+
32+ global $ argv ;
33+ array_shift ($ argv );
34+ array_shift ($ argv );
35+ array_unshift ($ argv , 'think ' , $ action );
36+ }
37+
38+ if ('start ' == $ action ) {
39+ $ output ->writeln ('Starting Websocket server... ' );
40+ }
41+
42+ $ option = Config::get ('worker_websocket ' );
43+
44+ if ($ input ->hasOption ('host ' )) {
45+ $ host = $ input ->getOption ('host ' );
46+ } else {
47+ $ host = !empty ($ option ['host ' ]) ? $ option ['host ' ] : $ configs ['host ' ];
48+ }
49+
50+ if ($ input ->hasOption ('port ' )) {
51+ $ port = $ input ->getOption ('port ' );
52+ } else {
53+ $ port = !empty ($ option ['port ' ]) ? $ option ['port ' ] : $ configs ['port ' ];
54+ }
55+
56+ if ($ input ->hasOption ('daemon ' )){
57+ $ option ['daemon ' ] = true ;
58+ } else {
59+ $ option ['daemon ' ] = !empty ($ option ['daemon ' ]) ? $ option ['daemon ' ] : $ configs ['daemon ' ];
60+ }
61+
62+ if (empty ($ option ['name ' ])){
63+ $ option ['name ' ] = $ configs ['name ' ];
64+ }
65+
66+ if (empty ($ option ['reuse_port ' ])){
67+ $ option ['reuse_port ' ] = $ configs ['reuse_port ' ];
68+ }
69+
70+ $ this ->start ($ host , (int ) $ port , $ option );
71+ }
72+
73+ public function start (string $ host , int $ port , array $ option = []){
74+ if (isset ($ option ['daemon ' ]) && $ option ['daemon ' ]){
75+ Worker::$ daemonize = true ;
76+ }
77+ $ ws_worker = new Worker ('websocket:// ' .$ host .': ' .$ port );
78+ $ ws_worker ->name = $ option ['name ' ]; // 名称
79+ $ ws_worker ->onConnect = function ($ connection ) {
80+ echo 'New connection: ' .$ connection ->getRemoteIp ();
81+ };
82+ $ ws_worker ->onMessage = function ($ connection , $ data ) use ($ option ) {
83+ $ connection ->send ('Hello ' . $ data );
84+ };
85+ $ ws_worker ->onClose = function ($ connection ) {
86+ echo "Connection closed " ;
87+ };
88+ Worker::runAll ();
89+ }
90+ }
0 commit comments