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();