简体   繁体   English

PHP websocket服务器和mysql连接

[英]PHP websocket server and mysql connection

I have a php websocket server based on this one .我有一个基于这个的 php websocket 服务器。 This websocket server runs on a different apache than the public webserver but on the same physical server so I need a database connection to retrieve userdata.这个 websocket 服务器运行在与公共 web 服务器不同的 apache 上,但在同一台物理服务器上,所以我需要一个数据库连接来检索用户数据。 The userdata is fetched by the current session id which is also updated in the database when a user loggs in. Now, if I run my websocket server it works perfect but after a decent time (can't say a timespan) the result stays empty.用户数据由当前会话 id 获取,当用户登录时,该会话 id 也会在数据库中更新。 现在,如果我运行我的 websocket 服务器,它运行良好,但经过一段时间(不能说时间跨度)后,结果保持为空. I checked the dataset.我检查了数据集。

The querystring is up to date and the correct session id is in the database which should return the desired row but the result stays empty.查询字符串是最新的,正确的会话 ID 在数据库中,它应该返回所需的行,但结果保持为空。 If I kill the process and run this websocket server, it will work for the time being but after a while the result is empty again.如果我终止进程并运行这个 websocket 服务器,它暂时可以工作,但过一段时间结果又是空的。

This is my websocketserver.php simplified:这是我的 websocketserver.php 简化版:

set_time_limit(0);
require 'class.PHPWebSocket.php';

$db1 = mysql_connect( 'localhost', 'dev', 'xxxxxxxx' );
mysql_select_db('cb_dev',$db1);

function wsOnMessage($clientID, $message, $messageLength, $binary) {
    global $Server;

    $sessionid = "/*just imagine a session id here*/";
    $result = mysql_query("SELECT username, id FROM users WHERE sessionid = '$sessionid'");
    $row = mysql_fetch_row($result);
}

function wsOnOpen($clientID) {
    //
}

function wsOnClose($clientID, $status) {
    //
}

$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');

$Server->wsStartServer('0.0.0.0', 9010);

Note: The used session id is served correctly so this is not the problem.注意:使用的会话 ID 已正确提供,因此这不是问题。

Swoole is a better choice for your requirement. Swoole是满足您需求的更好选择。 It support native websocket server & async mysql in PHP ,with ac extension它支持 PHP 中的原生 websocket 服务器和异步 mysql,带有 ac 扩展

WebSocket Server example: WebSocket 服务器示例:

$ws = new swoole_websocket_server("0.0.0.0", 9502);

$ws->on('open', function ($ws, $request) {
    var_dump($request->fd, $request->get, $request->server);
    $ws->push($request->fd, "hello, welcome\n");
});

$ws->on('message', function ($ws, $frame) {
    echo "Message: {$frame->data}\n";
    $ws->push($frame->fd, "server: {$frame->data}");
});

$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();

This is because your $sessionid was expired.这是因为您的 $sessionid 已过期。 Need to set higher timeout:需要设置更高的超时时间:

// 1 hour
ini_set('session.gc_maxlifetime', 3600);
session_set_cookie_params(3600);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM