首页 > 代码库 > 使用swoole websocket 实现执行console php文件 把输出返回给浏览器

使用swoole websocket 实现执行console php文件 把输出返回给浏览器

 1 swoole websocket 服务端
 2 <?php
 3 $server = new swoole_websocket_server("0.0.0.0", 9501);
 4 
 5 $server->on(‘open‘, function (swoole_websocket_server $server, $request) {
 6         echo "server: handshake success with fd{$request->fd}\n";
 7 });
 8 
 9 $server->on(‘message‘, function (swoole_websocket_server $server, $frame) {
10         #echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
11         if ($frame->data =http://www.mamicode.com/= 1) {
12                 $handle = popen(‘php ./console.php‘, ‘r‘);
13              while (!feof($handle)) { $content = fgets($handle);
14                         $server->push($frame->fd, $content);                        
15                 }
16                 pclose($handle);
17         }
18 });
19 
20 $server->on(‘close‘, function ($ser, $fd) {
21         echo "client {$fd} closed\n";
22 });
23 
24 $server->start();
 1 console.php脚本
 2 <?php
 3 
 4 echo ‘12‘.PHP_EOL;
 5 echo ‘34‘.PHP_EOL;
 6 
 7 sleep(10);
 8 echo ‘56‘.PHP_EOL;
 9 echo ‘78‘.PHP_EOL;
10 sleep(10);
11 echo ‘exit‘;
 1 前端脚本
 2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>Document</title>
 9 </head>
10 <body>
11     测试swoole websocket
12     <button type="button" class="btn btn-large btn-block btn-default" id="btn">点我</button>
13     <div id="show">
14 
15     </div>
16     <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
17     <script>
18         const socket = new WebSocket(‘ws://www.swoole-test.com:9501‘);
19 
20         // Connection opened
21         socket.addEventListener(‘open‘, function (event) {
22             socket.send(‘Hello Server!‘);
23         });
24 
25         // Listen for messages
26         socket.addEventListener(‘message‘, function (event) {
27             var data = http://www.mamicode.com/event.data;
28             console.log(data);
29         });
30 
31         $("#btn").on(‘click‘, function() {
32             socket.send(1);
33         });
34     </script>
35 </body>
36 </html>

执行swoole脚本 打开浏览器控制台 观察效果

使用swoole websocket 实现执行console php文件 把输出返回给浏览器