PHP fsockopen很慢

时间:2009-08-23 20:05:18

标签: php networking performance imap fsockopen

我正在使用fsockopen来发送和接收命令,在PHP中使用IMAP协议。我的初步实验工作但是非常慢。下面的简单功能大约需要2分钟才能运行。我已经尝试了几种不同的IMAP服务器,并得到了相同的结果。有谁能告诉我为什么这段代码太慢了?

<?php

function connectToServer($host, $port, $timeout) {
    // Connect to the server
    $conn = fsockopen($host, $port, $errno, $errstr, $timeout);

    // Write IMAP Command
    $command = "a001 CAPABILITY\r\n";

    // Send Command
    fputs($conn, $command, strlen($command));

    // Read in responses
    while (!feof($conn)) {
        $data .= fgets($conn, 1024);
    }

    // Display Responses
    print $data;

    // Close connection to server
    fclose($conn);
}

connectToServer('mail.me.com', 143, 30);

?>

这是我回复的回复:

macinjosh:Desktop Josh$ php test.php
* OK [CAPABILITY mmp0613 IMAP4 IMAP4rev1 ACL QUOTA LITERAL+ NAMESPACE UIDPLUS CHILDREN BINARY UNSELECT SORT LANGUAGE IDLE XSENDER X-NETSCAPE XSERVERINFO X-SUN-SORT X-SUN-IMAP X-ANNOTATEMORE X-UNAUTHENTICATE XUM1 AUTH=PLAIN STARTTLS] Messaging Multiplexor (Sun Java(tm) System Messaging Server 6.3-6.03 (built Jun  5 2008))
* CAPABILITY mmp0613 IMAP4 IMAP4rev1 ACL QUOTA LITERAL+ NAMESPACE UIDPLUS CHILDREN BINARY UNSELECT SORT LANGUAGE IDLE XSENDER X-NETSCAPE XSERVERINFO X-SUN-SORT X-SUN-IMAP X-ANNOTATEMORE X-UNAUTHENTICATE XUM1 AUTH=PLAIN STARTTLS
a001 OK CAPABILITY completed

1 个答案:

答案 0 :(得分:4)

似乎feof在远程端超时并关闭连接之前不会返回true。您传递的$timeout参数仅适用于初始连接尝试。

尝试更改while循环以直接打印状态:

while (!feof($conn)) {
    print fgets($conn, 1024);
}

或者在读取完整回复后将循环退出条件更改为中断。它可能必须更聪明的协议。

最后,我不得不问,你为什么不使用PHP的built-in IMAP client

相关问题