gateway中使用mysql

程序gg了

gateway使用mysql示例:http://doc2.workerman.net/mysql.html
我想在start_gateway.php中查询数据库,然后继续在events.php中使用要怎么做 ?

start_gateway.php我现在是使用file_get_content去GET查询数据库。

<?php 
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
use \Workerman\Worker;
use \Workerman\WebServer;
use \GatewayWorker\Gateway;
use \GatewayWorker\BusinessWorker;
use \Workerman\Autoloader;

// 自动加载类
require_once __DIR__ . '/../../vendor/autoload.php';

// gateway 进程,这里使用Text协议,可以用telnet测试
// $gateway = new Gateway("tcp://0.0.0.0:8282");
$gateway = new Gateway("websocket://0.0.0.0:2000");
// gateway名称,status方便查看
$gateway->name = 'Device';
// gateway进程数
$gateway->count = 1;
// 本机ip,分布式部署时使用内网ip
$gateway->lanIp = '127.0.0.1';
// 内部通讯起始端口,假如$gateway->count=4,起始端口为4000
// 则一般会使用4000 4001 4002 4003 4个端口作为内部通讯端口 
$gateway->startPort = 2900;
// 服务注册地址
$gateway->registerAddress = '127.0.0.1:1238';

// 心跳间隔
$gateway->pingInterval = 10;
$gateway->pingNotResponseLimit = 1;
// 心跳数据
//$gateway->pingData = '{"type":"ping"}';
$gateway->pingData = '';

// 当客户端连接上来时,设置连接的onWebSocketConnect,即在websocket握手时的回调
$gateway->onConnect = function($connection)
{
    $connection->onWebSocketConnect = function($connection , $http_header)
    {
        // $_SERVER 可用这里判断连接来源是否合法,不合法就关掉连接
        try
        {
            $url = 'http://ws.lzkdkeji.com/index/auth/index?data='.$_SERVER['REQUEST_URI'];
            $res = file_get_contents($url);
            if ( empty($res) ) throw new Exception('鉴权失败');
            $res = json_decode($res, TRUE);
            if ($res['code'] != 'success') throw new Exception($res['msg']);

            $_SESSION['device_data'] = $res['device_data'];
        }
        catch (\Exception $e)
        {
            echo $e->getMessage();
            $connection->close();
        }
    };
}; 

// 如果不是在根目录启动,则运行runAll方法
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}

怎么在start_gateway.php中使用mysql 并且不影响Events.php

<?php
use \GatewayWorker\Lib\Gateway;
require_once '/your/path/of/mysql-master/src/Connection.php';

/**
 * 数据库示例,假设有个your_db_name库,里面有个user表
 */
class Events
{
    /**
     * 新建一个类的静态成员,用来保存数据库实例
     */
    public static $db = null;

    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {
        self::$db = new \Workerman\MySQL\Connection('host', 'port', 'user', 'password', 'db_name');
    }

   /**
    * 有消息时触发该方法,根据发来的命令打印2个用户信息
    * @param int $client_id 发消息的client_id
    * @param mixed $message 消息
    * @return void
    */
   public static function onMessage($client_id, $message)
   {
        // 发来的消息
        $commend = trim($message);
        if($commend !== 'get_user_list')
        {
            Gateway::sendToClient($client_id, "unknown commend\n");
            return;
        }
        // 使用数据库实例
        self::$db->select('*')->from('users')->where('uid>3')->offset(5)->limit(2)->query();
        // 打印结果
        return Gateway::sendToClient($client_id, var_export($ret, true));
   }

}
3133 2 0
2个回答

six

我觉得最好不要在onConnect里做外部访问这些耗时的操作,连接量大了程序会越来越慢,万一访问外部资源卡了那么几秒,所有客户端跟着卡。你要鉴权不一定非要读数据库,客户端传递个token,onConnect里根据一定算法验证token是否合法就行了。

比如客户端后台生成token的算法

function token($uid) {
    $密钥 = 's#8id%2*!';
    $time = time();
    return 'token='.md5($密钥.$uid.$time)."&time=$time"&uid=$uid;
}

js连的时候 把token串带上 ws = new WebSocket('ws://example.com?{$token}');

Gateway端验证

$gateway->onConnect = function($connection)
{
    $connection->onWebSocketConnect = function($connection , $http_header)
    {
        $time = $_GET['time'];
        $uid = $_GET['uid'];
        $token = $_GET['token];
        $密钥='s#8id%2*!';
        // token 过60秒就失效,防止被窃取重复使用
        if (abs(time() - $time) < 60) return $connection->close();
        // token不合法就关闭连接
        if ($token != md5($密钥.$uid.$time)) {
            return $connection->close();
        }
        // 合法的话记录个uid的$_SESSION标记当前是谁,在Events.php可能用到
        $_SESSION['uid'] = $uid;
    }
}; 

密钥不要泄漏就行了

  • 程序gg了 2020-04-25

    我必须去数据库里面查询以下链接设备得密钥

  • six 2020-04-25

    上面密钥是一个公用的密钥,没必要去查。类似一个配置

程序gg了

求大佬解答下

  • 暂无评论
年代过于久远,无法发表回答
🔝