【发布时间】:2015-11-23 23:16:57
【问题描述】:
我编写了一个充当消息服务器的 php 脚本。消息服务器使用 websockets 在多个移动应用程序之间建立连接,以便在不同应用程序之间提供实时聊天功能。
messageserver.php 脚本的主要布局如下所示:
#!/usr/bin/env php
<?php
class chatServer extends WebSocketServer {
var $usersCache = array();
var $userConnectionIds = array();
var $dbconnect;
public function setDatabaseConnection($connect) {
$this->dbconnect = $connect;
}
private function addMessage($convId, $from, $to, $message, $read) {
..
}
protected function process ($user, $message) {
$parsedMessage = json_decode($message, true);
switch($parsedMessage["type"]) {
case "handshake" :
$this->usersCache[$parsedMessage["userId"]] = $user;
$this->userConnectionIds[$user->id] = $parsedMessage["userId"];
break;
case "chatMessage" :
$receivingUser = $this->usersCache[$parsedMessage["to"]];
if ($receivingUser != null) {
$returnValue = $this->send($receivingUser, json_encode($parsedMessage));
}
}
}
protected function connected ($user) {
}
protected function closed ($user) {
$userId = $this->userConnectionIds[$user->id];
unset($this->userConnectionIds[$user->id]);
unset($this->usersCache[$userId]);
var_dump($this->usersCache);
}
}
$chatServer = new chatServer("0.0.0.0","36092");
global $connect;
try {
$chatServer->setDatabaseConnection($connect);
$chatServer->run();
}
catch (Exception $e) {
$echo->stdout($e->getMessage());
}
为了让messageserver.php在我使用的服务器上运行
nohup php messageServer.php > php.log 2>&1 &
这应该允许服务继续运行,即使我关闭了与服务器的 ssh 连接,情况确实如此。现在我的问题是这个设置按预期工作,没有任何问题。然而,一段时间后,php 脚本停止运行,根本没有任何消息。 php.log 文件不包含任何类型的错误或终止消息。有人知道这里会发生什么吗?有什么方法可以跟踪服务停止运行的原因吗?谢谢!
【问题讨论】:
-
我认为追踪这一点的唯一方法是临时添加调试语句,每隔一分钟左右将当前状态变量和数据库状态写入日志文件。如果这不起作用,请在调用函数时为函数添加更多调试语句。有些东西正在扼杀你的进程,我们需要找出它是什么。它可能是丢失的数据库连接或传递给它的错误参数或带有无效引用的代码行或其他东西的函数阻塞。
-
我不是专家,但在我作为 PHP 编码员的时代(很久以前),PHP 进程自然是短暂的。 Http 服务器要么延长进程的生命周期,要么为新的 Http 请求启动一个新进程。如果前一个进程没有关闭监听套接字并且资源没有被释放,那么启动一个新进程可能会失败...... PHP 有它的优势,但长时间运行的进程不是其中之一。我会考虑为 websocket 层切换到 Ruby、node.js 或 Python。
标签: php service websocket server phpwebsocket