[PHP] php as the client of websocket reads the push log file in real time

First, you need to use composer to download a third-party extension to realize the websocket client of php. You can directly generate the composer.json file in the current directory
composer require textalk/websocket

use WebSocket\Client;
$client = new Client("ws://echo.websocket.org/");
$client->send("Hello WebSocket.org!");
echo $client->receive();

With php's read file operation, only the latest additional content is read. The following code is the client reading the log and sent to 10.xx.2.xx:9501

#!/usr/bin/env php 

use WebSocket\Client;

if(2 != count($argv)){
        "Call format error! Use format ./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/");
    $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);
        //Direct output content
        // fwrite(
        //     STDOUT,
        //     fread($fp, $add_size)
        // );  
        $client->send(fread($fp, $add_size));
        $file_size  = $file_size_new;


The code of the server uses swoole as the server, broadcasts to all connections after receiving the message, and executes the server

$server = new Swoole\WebSocket\Server("", 9501);
$server->on('open', function (Swoole\WebSocket\Server $server, $request)use($fds) {
    echo "server: handshake success with fd{$request->fd}\n";

$server->on('message', function (Swoole\WebSocket\Server $server, $frame)use($fds) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    foreach($server->connections as $fd){
        $server->push($fd, $frame->data);

$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";





Execute client



It can output directly in real time in the browser

Keywords: PHP JSON

Added by clodagh2000 on Mon, 06 Jan 2020 05:32:20 +0200