12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <?php
- use Workerman\Worker;
- use Workerman\Lib\Timer;
- use PHPSocketIO\SocketIO;
- require_once __DIR__ . '/vendor/autoload.php';
- // Listen port 2021 for socket.io client
- // 文档:https://github.com/walkor/phpsocket.io/tree/master/docs/zh
- $conn_pools = [];
- $io = new SocketIO(2346);
- $io->on('connection', function ($socket) use ($io, $conn_pools) {
- echo 'socket connected '.$socket->handshake['address'].PHP_EOL;
- //var_dump($socket->handshake);
- //$conn_pools[$socket->handshake['address']] = $socket;
- //var_dump($socket);
- $socket->on('disconnect', function () use($socket, $conn_pools) {
- echo 'socket disconnected '.$socket->handshake['address'].PHP_EOL;
- //从连接池移除
- //unset($conn_pools[$socket->handshake['address']]);
- });
- });
- $io->on('workerStart', function()use($io, $conn_pools) {
-
- // 定时,每10秒一次
- Timer::add(30, function()use($io, $conn_pools)
- {
-
- $servername = "127.0.0.1";
- $username = "root";
- $password = "abc123@lzmLZM";
- $dbname = "catch_admin_renlian";
-
- // 创建连接
- $conn = new mysqli($servername, $username, $password, $dbname);
- // Check connection
- if ($conn->connect_error) {
- die("连接失败: " . $conn->connect_error);
- }
- /*
- if(!$conn_pools) {
- echo '[Timer] no connections'.PHP_EOL;
- return;
- }*/
- $sql = "SELECT id FROM alarm_records";
- $result = $conn->query($sql);
- $conn->close();
- $count = $result->num_rows;
- if ($count <= 0) {
- echo 'no alarm msg'.PHP_EOL;
- return;
- }
- $msg = [
- 'content' => '当前未处理告警'.$count.'条',
- 'title' => '告警提示'
- ];
-
- //向当前客户端发送事件
- //$socket->emit('event name', $data);
-
- //向所有客户端发送事件
- $io->emit('alarm_notify', $msg);
-
- //向某个分组的所有客户端发送事件
- //$io->to('group name')->emit('event name', $data);
- });
- });
- Worker::runAll();
|