簡體   English   中英

PHP UDP套接字內存泄漏

[英]PHP UDP socket memory leak

我有一段PHP代碼,這是一個非常基本的UDP服務器。 問題在於它存在內存泄漏,這使我發瘋。

事實/觀察:-如果腳本僅自行啟動,它將耗盡內存。 -當我輸出內存使用情況或while循環中的任何文本時,它不會崩潰,並且顯示一致的內存使用情況。 -但是,當客戶端連接到服務器時,while循環的每次迭代都會消耗額外的96字節內存,直到崩潰。 客戶端甚至不需要發送數據。 實際上,大多數迭代由process()函數中的第一個IF語句(如果緩沖區為空)處理,然后返回。 -為腳本/進程分配更多的內存只會將不可避免的崩潰延遲更長的時間。 -從CentOS 6上的PHP5.3.3升級到5.4並沒有幫助。

任何幫助或指針,將不勝感激!

<?php

ini_set( 'display_errors', true );

class UDP_Server {

    protected $_socket = null;
    protected $_host = '';
    protected $_port = 0;
    protected $_clients = array();
    protected $_debug = false;

    public function __construct( $host = '', $port = 0 ) {
        $this->_host = $host;
        $this->_port = $port;
        $this->_socket = $this->_create_udp_server( $host, $port );
    }

    public function set_debug( $value = false ) {
        $this->_debug = $value;
    }

    public function process() {
        $buffer = stream_socket_recvfrom( $this->_socket, 1024, 0, $remote_host );
        if( empty( $buffer ) ) {
            return;
        }

        if( $this->_debug ) {
            echo $remote_host, ': ', $buffer, "\n";
        }

        if( strpos( $buffer, 'udp.register.ip' ) !== false ) {
            if( ! in_array( $remote_host, $this->_clients ) ) {
                $this->_clients[] = $remote_host;
            }

            stream_socket_sendto( $this->_socket, 'udp.register.complete', 0, $remote_host );
            return;
        }

        foreach( $this->_clients as $client ) {
            if( $client === $remote_host ) {
                continue;
            }
            stream_socket_sendto( $this->_socket, $buffer, 0, $client );
        }
    }

    public function __destruct() {
        fclose( $this->_socket );
    }

    protected static function _create_udp_server( $host = '0.0.0.0', $port = 0 ) {
        $address = 'udp://' . $host . ':' . $port;
        $socket = stream_socket_server( $address, $error_number, $error_message, STREAM_SERVER_BIND );
        if( ! $socket ) {
            die( 'could not create UDP server for ' . $address . '; Reason: [' . $error_number . '] - ' . $error_message );
        }

        stream_set_blocking( $socket, 0 );
        return $socket;
    }

}

$at_data_server  = new UDP_Server( '0.0.0.0', 5556 );
$at_data_server->set_debug( true );

while( 1 ) {
    $at_data_server->process();
}

看來您的代碼符合此錯誤報告中的條件-https: //bugs.php.net/bug.php?id=71613

如果可能,請避免使用stream_socket_recvfrom()的第四個參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM