start.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. use Workerman\Worker;
  3. use Workerman\Lib\Timer;
  4. use PHPSocketIO\SocketIO;
  5. require_once __DIR__ . '/vendor/autoload.php';
  6. // Listen port 2021 for socket.io client
  7. // 文档:https://github.com/walkor/phpsocket.io/tree/master/docs/zh
  8. $conn_pools = [];
  9. $io = new SocketIO(2346);
  10. $io->on('connection', function ($socket) use ($io, $conn_pools) {
  11. echo 'socket connected '.$socket->handshake['address'].PHP_EOL;
  12. //var_dump($socket->handshake);
  13. //$conn_pools[$socket->handshake['address']] = $socket;
  14. //var_dump($socket);
  15. $socket->on('disconnect', function () use($socket, $conn_pools) {
  16. echo 'socket disconnected '.$socket->handshake['address'].PHP_EOL;
  17. //从连接池移除
  18. //unset($conn_pools[$socket->handshake['address']]);
  19. });
  20. });
  21. $io->on('workerStart', function()use($io, $conn_pools) {
  22. // 定时,每10秒一次
  23. Timer::add(30, function()use($io, $conn_pools)
  24. {
  25. $servername = "127.0.0.1";
  26. $username = "root";
  27. $password = "abc123@lzmLZM";
  28. $dbname = "catch_admin_renlian";
  29. // 创建连接
  30. $conn = new mysqli($servername, $username, $password, $dbname);
  31. // Check connection
  32. if ($conn->connect_error) {
  33. die("连接失败: " . $conn->connect_error);
  34. }
  35. /*
  36. if(!$conn_pools) {
  37. echo '[Timer] no connections'.PHP_EOL;
  38. return;
  39. }*/
  40. $sql = "SELECT id FROM alarm_records";
  41. $result = $conn->query($sql);
  42. $conn->close();
  43. $count = $result->num_rows;
  44. if ($count <= 0) {
  45. echo 'no alarm msg'.PHP_EOL;
  46. return;
  47. }
  48. $msg = [
  49. 'content' => '当前未处理告警'.$count.'条',
  50. 'title' => '告警提示'
  51. ];
  52. //向当前客户端发送事件
  53. //$socket->emit('event name', $data);
  54. //向所有客户端发送事件
  55. $io->emit('alarm_notify', $msg);
  56. //向某个分组的所有客户端发送事件
  57. //$io->to('group name')->emit('event name', $data);
  58. });
  59. });
  60. Worker::runAll();