zoukankan      html  css  js  c++  java
  • [PHP] php作为websocket的客户端实时读取推送日志文件

    首先要使用composer来下载一个第三方扩展就可以实现php的websocket客户端,直接在当前目录生成下composer.json文件就可以了
    composer require textalk/websocket

    require('vendor/autoload.php');
    use WebSocketClient;
    $client = new Client("ws://echo.websocket.org/");
    $client->send("Hello WebSocket.org!");
    echo $client->receive();

    配合php的读取文件操作,只读取最新的追加的内容,下面代码为读取日志的客户端 , 发送给10.xx.2.xx:9501

    #!/usr/bin/env php 
    <?php
    require('vendor/autoload.php');
    
    use WebSocketClient;
    
    if(2 != count($argv)){
        fwrite(
            STDERR,
            "调用格式错误!使用格式 ./xxx filename".PHP_EOL
        );  
        return 1;
    }
    
    $file_name      = $argv[1];
    define("MAX_SHOW", 8192);
    
    $file_size      = 0;
    $file_size_new  = 0;
    $add_size       = 0;
    $ignore_size    = 0;
    $fp = fopen($file_name, "r");
    $client = new Client("ws://10.xx.2.xx:9501/");
    while(1){
        clearstatcache();
        $file_size_new  = filesize($file_name);
        $add_size       = $file_size_new - $file_size;
        if($add_size > 0){ 
            if($add_size > MAX_SHOW){
                $ignore_size    = $add_size - MAX_SHOW;
                $add_size       = MAX_SHOW;
                fseek($fp, $file_size + $ignore_size);
            }   
            //直接输出内容
            // fwrite(
            //     STDOUT,
            //     fread($fp, $add_size)
            // );  
            $client->send(fread($fp, $add_size));
            $file_size  = $file_size_new;
        }
        usleep(50000);
    }
    
    fclose($fp);

    服务端的代码使用swoole作为服务端,并且在收到消息后给所有的连接广播,执行服务端

    <?php
    $server = new SwooleWebSocketServer("0.0.0.0", 9501);
    $server->on('open', function (SwooleWebSocketServer $server, $request)use($fds) {
        echo "server: handshake success with fd{$request->fd}
    ";
    });
    
    $server->on('message', function (SwooleWebSocketServer $server, $frame)use($fds) {
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}
    ";
        foreach($server->connections as $fd){
            $server->push($fd, $frame->data);
        }
    });
    
    $server->on('close', function ($ser, $fd) {
        echo "client {$fd} closed
    ";
    });
    
    $server->start();

    执行客户端

     可以在浏览器直接实时输出

  • 相关阅读:
    SugarCRM 主表自定义字段日期型
    算法导论46 VLSI芯片测试
    算法导论14.18
    算法导论13.24
    poj1980 Unit Fraction Partition **
    算法导论5.12
    算法导论76 对区间的模糊排序
    红黑树(redblack tree)算法,附AVL树的比较
    poj1856 Sea Battle *
    算法导论42 找出所缺的整数
  • 原文地址:https://www.cnblogs.com/taoshihan/p/12146540.html
Copyright © 2011-2022 走看看