public function onMessage($connection, $data)
{
global $worker;
$connection->lastMessageTime = time();
$data = json_decode($data, true);
$_SESSION['hotel_price'] = '';
switch($data['type']){
case 'login':
$where['id'] = $data['id'];
$where['token'] = $data['token'];
$id = Db::name('business')->where($where)->value('id');
if($id){
$connection->uid = $id;//設置當前客戶端id
$worker->uidConnections[$connection->uid] = $connection;//保存到服務器里
$connection->send('{"type":"login","msg":"登錄成功"}');
$timer = new Timer();
$connection->timer_id = $timer->add('10',function()use($connection,$data){
$connection->send('{"type":"ping"}');
});
}else{
$connection->timer_id = '';
$connection->uid = $data['id'].$data['token'];
$worker->uidConnections[$connection->uid] = $connection;//保存到服務器里
$connection->send('{"type":"login","msg":"登錄失敗"}');
$connection->close();
}
break;
}
}
如果用戶多點了一次login的話 定時器就會形成兩個ping到客戶端了 各位大神 怎么解決?
首先你需要多看下文檔,定時器不建議寫在onMessage回調(diào)。
從你代碼中大致得出定時器主要做一件事:那就是心跳檢測。
如下為大概示例:
<?php
?
require_once __DIR__ . '/Workerman/Autoloader.php';
?
?
use Workerman\Worker;
use Workerman\Lib\Timer;
$worker = new Worker('tcp://0.0.0.0:1234');
$worker->onWorkerStart = function($worker) {
// 防止開多進程
if ($worker->id === 0) {
Timer::add(10, function()use($worker) {
foreach($worker->connections as $connection) {
$connection->send('{"type":"ping"}');
}
});
}
};
?
$worker->onConnect = function($connection) {
};
$worker->onMessage = function($connection, $data) {
global $worker;
$connection->lastMessageTime = time();
$data = json_decode($data, true);
$_SESSION['hotel_price'] = '';
switch ($data['type']) {
case 'login':
$where['id'] = $data['id'];
$where['token'] = $data['token'];
$id = Db::name('business')->where($where)->value('id');
if ($id) {
$connection->uid = $id; //設置當前客戶端id
$worker->uidConnections[$connection->uid] = $connection; //保存到服務器里
$connection->send('{"type":"login","msg":"登錄成功"}');
} else {
$connection->timer_id = '';
$connection->uid = $data['id'] . $data['token'];
$worker->uidConnections[$connection->uid] = $connection; //保存到服務器里
$connection->send('{"type":"login","msg":"登錄失敗"}');
$connection->close();
}
break;
}
};
// 如果不是在根目錄啟動,則運行runAll方法
if(!defined('GLOBAL_START')) {
Worker::runAll();
}
如果不放到onMessage里,那用戶send驗證賬戶密碼怎么做,驗證登錄密碼后 我們要實時返回數(shù)據(jù)給用戶呢,我現(xiàn)在的情況是 可能用戶多點了一次login 我們的服務器會返回兩次數(shù)據(jù),重復了 怎么樣避免這樣的問題呢?