1

PHP ソケット接続を使用してサーバーを定期的にポーリングしようとしています。ただし、スクリプトを実行すると、最初は正しい動作が得られますが、2 回目は次のエラーが発生します。

fsockopen(): php_network_getaddresses: getaddrinfo failed: Name or service not known

スクリプトを 3 回目に実行すると、次のエラーが表示されます。

fsockopen(): unable to connect to :0 (Failed to parse address "")

そのエラーは、その後の試行ごとに繰り返されます。ただし、約 1 分待ってから再試行すると、すべてが機能します。ソケット接続が閉じず、再度作成しようとすると拒否されるという問題があるように思えます。

ソケット通信を処理するクラスは次のとおりです。

class FsSocket
{   
private $password = "XXXXXXXXXX";
private $port = "8030";
private $host = "hostname";

function event_socket_create( $host=null, $port=null, $password=null ) {
    if ( $host == null ) {
        $host = $this->host;
    }
    if ( $port == null ) {
        $port = $this->port;
    }
    if ( $password == null ) {
        $password = $this->password;
    }

    error_log( $host.":".$port );
    $fp = fsockopen($host, $port, $errno, $errdesc, 2) or die("Connection to $host failed");
    socket_set_blocking($fp,false);

    if ($fp) {
        while (!feof($fp)) {
            $buffer = fgets($fp, 1024);
            usleep(100); //allow time for reponse
            if (trim($buffer) == "Content-Type: auth/request") {
            fputs($fp, "auth $password\n\n");
            break;
            }
        }
        return $fp;
    }
    else {
        return false;
    }           
}


function event_socket_request($fp, $cmd) {

    if ($fp) {    
        fputs($fp, $cmd."\n\n");    
        usleep(100); //allow time for reponse

        $response = "";
        $i = 0;
        $contentlength = 0;
        while (!feof($fp)) {
            $buffer = fgets($fp, 4096);
            if ($contentlength > 0) {
            $response .= $buffer;
            }

            if ($contentlength == 0) { //if contentlenght is already don't process again
                if (strlen(trim($buffer)) > 0) { //run only if buffer has content
                    $temparray = explode(":", trim($buffer));
                    if ($temparray[0] == "Content-Length") {
                        $contentlength = trim($temparray[1]);
                    }
                }
            }

            usleep(100); //allow time for reponse

            //optional because of script timeout //don't let while loop become endless
            if ($i > 10000) { break; } 

            if ($contentlength > 0) { //is contentlength set
                //stop reading if all content has been read.
                if (strlen($response) >= $contentlength) {  
                break;
                }
            }
            $i++;
        }

        return $response;
    }
    else {
    echo "no handle";
    }
}
}

ソケット クラスを呼び出すコードは次のとおりです。

$socket = new FsSocket();
$fp = $socket->event_socket_create();

$cmd = "sofia_contact $to->user@$to->domain";
$response = $socket->event_socket_request($fp, $cmd);

fclose($fp);
unset($socket);

ループビットはまだ実装していません。最初にページを手動で更新して、これを機能させようとしています。

4

0 に答える 0