php输出流到客户端,php – 流FTP下载到输出

找到解决方案!

创建套接字对(匿名管道?).使用非阻塞ftp_nb_fget函数写入管道的一端,并回显管道的另一端.

测试速度很快(在100Mbps连接上容易10MB / s),所以没有太多的I / O开销.

确保清除任何输出缓冲区.框架通常会缓冲输出.

public function echo_contents() {

/* FTP writes to [0]. Data passed through from [1]. */

$sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);

if($sockets === FALSE) {

throw new Exception('Unable to create socket pair');

}

stream_set_write_buffer($sockets[0], 0);

stream_set_timeout($sockets[1], 0);

try {

// $this->ftp is an FtpConnection

$get = $this->ftp->get_non_blocking($this->path, $sockets[0]);

while(!$get->is_finished()) {

$contents = stream_get_contents($sockets[1]);

if($contents !== false) {

echo $contents;

flush();

}

$get->resume();

}

$contents = stream_get_contents($sockets[1]);

if($contents !== false) {

echo $contents;

flush();

}

} catch(Exception $e) {

fclose($sockets[0]); // wtb finally

fclose($sockets[1]);

throw $e;

}

fclose($sockets[0]);

fclose($sockets[1]);

}

// class FtpConnection

public function get_non_blocking($path, $stream) {

// $this->ftp is the FTP resource returned by ftp_connect

return new FtpNonBlockingRequest($this->ftp, $path, $stream);

}

/* TODO Error handling. */

class FtpNonBlockingRequest {

protected $ftp = NULL;

protected $status = NULL;

public function __construct($ftp, $path, $stream) {

$this->ftp = $ftp;

$this->status = ftp_nb_fget($this->ftp, $stream, $path, FTP_BINARY);

}

public function is_finished() {

return $this->status !== FTP_MOREDATA;

}

public function resume() {

if($this->is_finished()) {

throw BadMethodCallException('Cannot continue download; already finished');

}

$this->status = ftp_nb_continue($this->ftp);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值