1

我正在尝试使用 PHP 套接字连接定期轮询服务器。但是,当我第一次运行脚本时,我得到了正确的行为,但第二次出现以下错误:

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

当我第三次运行脚本时,出现以下错误:

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

随后的每次尝试都会重复该错误。但是,如果我等待大约一分钟并重试,那么一切正常。在我看来,当我尝试再次创建它时,我遇到了套接字连接没有关闭然后被拒绝的问题。

处理套接字通信的类是:

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类的代码如下:

$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