我在一些基于浏览器的游戏中使用Ratchet作为套接字服务器,我注意到了一个非常奇怪的行为。
我的应用程序类实现了WampServerInterface,我注意到在4-5个客户端通过autobahn.js连接和断开连接后,会有大约300KB的内存卡住。然后,如果另外7-8个客户端连接和断开连接,内存使用量不会增加。只有当10-12个新客户端连接和断开时,它才会增加,所以我有一种印象它正在重复使用内存,但我仍然担心当许多客户端连接到服务器时可能会导致内存泄漏。
然后我决定进行一些测试,我制作了一个实现MessageComponentInterface的应用程序类(这样我就可以使用telnet连接)。下面是启动服务器的代码:
最终,我编写了一个bash脚本来连接和断开连接,这个脚本会在一个无限循环中运行。
在运行bash脚本后,我注意到相同的行为 - 几个周期后,内存使用量增加了。这个问题是否与Ratchet(或React)有关,还是仅仅是PHP的问题?我忘记提到我使用启用了GC的PHP 5.5.3。
我的应用程序类实现了WampServerInterface,我注意到在4-5个客户端通过autobahn.js连接和断开连接后,会有大约300KB的内存卡住。然后,如果另外7-8个客户端连接和断开连接,内存使用量不会增加。只有当10-12个新客户端连接和断开时,它才会增加,所以我有一种印象它正在重复使用内存,但我仍然担心当许多客户端连接到服务器时可能会导致内存泄漏。
然后我决定进行一些测试,我制作了一个实现MessageComponentInterface的应用程序类(这样我就可以使用telnet连接)。下面是启动服务器的代码:
<?php
ini_set('display_errors', 'On');
require 'vendor/autoload.php';
require 'bootstrap.php';
use Ratchet\Server\IoServer;
use AsterMedia\Games\Socket;
$server = IoServer::factory(
new Socket(),
9090,
'127.0.0.1'
);
$server->run();
?>
我的应用程序类非常简单,看起来像这样:
<?php
namespace AsterMedia\Games;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Socket implements MessageComponentInterface {
public function onClose(ConnectionInterface $conn) {
echo "Client disconnected" . $this->getMemoryUsage() . PHP_EOL;
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
public function onOpen(ConnectionInterface $conn) {
echo "Client connected" . $this->getMemoryUsage() . PHP_EOL;
}
public function onMessage(ConnectionInterface $from, $msg) {
echo $msg . PHP_EOL;
}
private function getMemoryUsage() {
return sprintf('[Memory usage (currently) %dKB/ (max) %dKB]', round(memory_get_usage(true) / 1024), memory_get_peak_usage(true) / 1024);
}
}
最终,我编写了一个bash脚本来连接和断开连接,这个脚本会在一个无限循环中运行。
while true
do
echo "connect"
exec 3<>/dev/tcp/127.0.0.1/9090
exec 3<&-
echo "disconnect"
sleep 1
done
在运行bash脚本后,我注意到相同的行为 - 几个周期后,内存使用量增加了。这个问题是否与Ratchet(或React)有关,还是仅仅是PHP的问题?我忘记提到我使用启用了GC的PHP 5.5.3。