使用fgets/fread挂起从fsockopen读取数据 [英] Reading data from fsockopen using fgets/fread hangs
问题描述
这是我正在使用的代码:
Here is the code that I am using:
if (!($fp = fsockopen('ssl://imap.gmail.com', '993', $errno, $errstr, 15)))
echo "Could not connect to host";
$server_response = fread($fp, 256);
echo $server_response;
fwrite($fp, "C01 CAPABILITY"."\r\n");
while (!feof($fp)) {
echo fgets($fp, 256);
}
我得到第一个答复:
OK Gimap ready for requests from xx.xx.xx.xx v3if9968808ibd.15
,但是页面超时.我已经搜索了stream_set_blocking,stream_set_timeout,stream_select,fread等,但是无法使其正常工作.我需要读取服务器发送的所有数据,然后执行其他命令(我将使用imap检索电子邮件).
but then the page times out. I have searched through stream_set_blocking, stream_set_timeout, stream_select, fread, etc. but could not get it to work. I need to read all the data that the server sends and then proceed with other commands (I would be retrieving emails using imap).
谢谢
推荐答案
您的脚本最后挂在while循环中.这是因为您已使用!feof()
作为循环条件,并且服务器没有关闭连接.这意味着feof()
将始终返回false
,并且循环将永远继续.
Your script is hanging in the while loop at the end. This is because you have used !feof()
as the condition for the loop, and the server is not closing the connection. This means the feof()
will always return false
and the loop will continue forever.
当您编写完整的实现时,这不会有问题,因为您将寻找响应代码并且可能会相应地跳出循环,例如:
This will not be problem when your write a full implementation, as you will be looking for response codes and can break out of the loop accordingly, for example:
<?php
// Open a socket
if (!($fp = fsockopen('ssl://imap.gmail.com', 993, $errno, $errstr, 15))) {
die("Could not connect to host");
}
// Set timout to 1 second
if (!stream_set_timeout($fp, 1)) die("Could not set timeout");
// Fetch first line of response and echo it
echo fgets($fp);
// Send data to server
echo "Writing data...";
fwrite($fp, "C01 CAPABILITY\r\n");
echo " Done\r\n";
// Keep fetching lines until response code is correct
while ($line = fgets($fp)) {
echo $line;
$line = preg_split('/\s+/', $line, 0, PREG_SPLIT_NO_EMPTY);
$code = $line[0];
if (strtoupper($code) == 'C01') {
break;
}
}
echo "I've finished!";
这篇关于使用fgets/fread挂起从fsockopen读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!