首先要使用composer来下载一个第三方扩展就可以实现php的websocket客户端,直接在当前目录生成下composer.json文件就可以了
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();
配合php的读取文件操作,只读取最新的追加的内容,下面代码为读取日志的客户端 , 发送给10.xx.2.xx:9501
#!/usr/bin/env php <?php require(‘vendor/autoload.php‘); use WebSocket\Client; 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 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();
执行客户端
可以在浏览器直接实时输出
原文地址:https://www.cnblogs.com/taoshihan/p/12146540.html
时间: 2024-11-09 04:42:24