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
require('vendor/autoload.php'); 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 <?php require('vendor/autoload.php'); use WebSocket\Client; if(2 != count($argv)){ fwrite( STDERR, "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/"); 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); } //Direct output content // fwrite( // STDOUT, // fread($fp, $add_size) // ); $client->send(fread($fp, $add_size)); $file_size = $file_size_new; } usleep(50000); } fclose($fp);
The code of the server uses swoole as the server, broadcasts to all connections after receiving the message, and executes the server
<?php $server = new Swoole\WebSocket\Server("0.0.0.0", 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"; }); $server->start();
Execute client
It can output directly in real time in the browser