123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138 |
- <?php
- namespace app\push\controller;
- use think\Db;
- use think\worker\Server;
- use Workerman\Lib\Timer;
- class Worker extends Server
- {
- protected $socket = 'websocket://0.0.0.0:2346';
- protected $snConnections = [];
- protected $heartbeat_time = '55';
-
- public function onMessage($connection, $datas)
- {
- $connection->lastMessageTime = time();
- $data = json_decode($datas);
- if (empty($data->uid)) {
- $connection->close();
- return;
- }
- $uid = 1;
- if (empty($uid)) {
- $connection->close();
- return;
- }
- switch ($data->type) {
- case 'login':
-
- $this->uidConnections[$uid] = $connection;
-
- break;
- case 'send':
-
-
- break;
- }
- }
-
- public function onConnect($connection)
- {
- $connection->send('链接成功');
- }
-
- public function onClose($connection)
- {
- if(isset($connection->uid))
- {
-
- unset($this->uidConnections[$connection->uid]);
- }
- }
-
- public function onError($connection, $code, $msg)
- {
- echo "error $code $msg\n";
- }
-
- public function onWorkerStart($worker)
- {
-
- $inner_text_worker = new \Workerman\Worker('text://0.0.0.0:2347');
-
- $inner_text_worker->onMessage = function ($connection, $buffer) {
-
- $data = json_decode($buffer, true);
- $uid = $data['uid'];
-
- $ret = $this->sendMessageByUid($uid, $buffer);
-
- $connection->send($ret ? 'ok' : 'fail');
- };
-
- $inner_text_worker->listen();
- Timer::add(10, function()use($worker){
- $time_now = time();
- foreach($worker->connections as $connection) {
-
- if (empty($connection->lastMessageTime)) {
- $connection->lastMessageTime = $time_now;
- continue;
- }
- $diff_time = $time_now - $connection->lastMessageTime;
- $msg = '距离上次通话已经过去'.$diff_time.'秒';
- $connection->send($msg);
-
- if ($time_now - $connection->lastMessageTime > $this->heartbeat_time) {
- $connection->close();
- }
- }
- });
- }
-
- public function broadcast($message)
- {
- foreach($this->uidConnections as $connection)
- {
- $connection->send($message);
- }
- }
-
- public function sendMessageByUid($uid, $message)
- {
- if(isset($this->uidConnections[$uid]))
- {
- $connection = $this->uidConnections[$uid];
- $connection->send($message);
- return true;
- }
- return false;
- }
- }
|