• 使用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}
    ";
     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}
    ";
    11         if ($frame->data == 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
    ";
    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 = 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脚本 打开浏览器控制台 观察效果

  • 相关阅读:
    JasperReports项目中的应用
    请问两个div之间的上下距离怎么设置
    Spring MVC Flash Attribute 的讲解与使用示例
    8.ireport 取消自动分页,detail不分页
    python网络爬虫学习笔记
    ShareSDK for Android 2.3.8它已发表
    OllyDbg 使用注意事项 (十)
    ListView的cacheColorHint与listSelector物业和fragment里面onActivityResult问题没有响应
    Hdu 3341 Lost&#39;s revenge (ac+自己主动机dp+hash)
    PhoneGap 开发与应用 上传 App Store 在
  • 原文地址:https://www.cnblogs.com/a-flydog/p/7073764.html
Copyright © 2020-2023  润新知