ShTcp.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace app\workerman;
  3. use app\common\server\ShOneanalysis;
  4. use think\facade\Log;
  5. use think\worker\Server;
  6. use Workerman\Lib\Timer;
  7. class ShTcp extends Server
  8. {
  9. //protected $socket = 'tcp://0.0.0.0:21444';
  10. protected $socket = 'tcp://0.0.0.0:9501';
  11. protected function init()
  12. {
  13. $this->count = 4; //线程数
  14. }
  15. public function onConnect($connection)
  16. {
  17. }
  18. public function onWorkerStart($worker)
  19. {
  20. define('HEARTBEAT_TIME', 1000);
  21. //异步处理
  22. $server_sa = new ShOneanalysis();
  23. Timer::add(1, function () use ($worker, $server_sa) {
  24. if (isset($worker->device_id_code)) {
  25. $device_id_code = $worker->device_id_code;
  26. foreach ($worker->connections as $connection) {
  27. $info = $server_sa->getsendqueuelist($device_id_code);
  28. $totalpage = $info['totalpage'];
  29. if ($totalpage > 0) {
  30. $size = $info['size'];
  31. for ($page = 1; $page <= $totalpage; $page++) {
  32. $list = $server_sa->getsendqueuelist($device_id_code, 1, $size);
  33. foreach ($list as $key => $value) {
  34. $connection->send(json_encode($value['msg']));
  35. $server_sa->sendmsgsuccess($value);
  36. }
  37. }
  38. }
  39. }
  40. }
  41. });
  42. Timer::add(1, function () use ($worker) {
  43. $time_now = time();
  44. foreach ($worker->connections as $connection) {
  45. // 有可能该connection还没收到过消息,则lastMessageTime设置为当前时间
  46. if (empty($connection->lastMessageTime)) {
  47. $connection->lastMessageTime = $time_now;
  48. continue;
  49. }
  50. // 上次通讯时间间隔大于心跳间隔,则认为客户端已经下线,关闭连接
  51. if ($time_now - $connection->lastMessageTime > HEARTBEAT_TIME) {
  52. //$connection->close();
  53. //设置对应设备下线
  54. }
  55. }
  56. });
  57. }
  58. public function onMessage($connection, $data)
  59. {
  60. Log::write("ShTcp", 'shouhuan');
  61. Log::write($data, 'shouhuan');
  62. $server_sa = new ShOneanalysis();
  63. $result = $server_sa->savereceivequeue($data);
  64. if (empty($result)) {
  65. Log::write("手环接收信息队列,数据保存失败", 'shouhuan');
  66. }
  67. //$line = $server_sa->getline($data);
  68. //$this->device_id_code = $line['device_id_code'];
  69. $this->device_id_code = "358800006072996";
  70. }
  71. public function onClose($connection)
  72. {
  73. }
  74. }