gpt4 book ai didi

rust - Libssh2停止读取大文件

转载 作者:行者123 更新时间:2023-12-03 11:44:36 36 4
gpt4 key购买 nike

我需要通过ssh读取一些文件,但是当我循环读取该文件时...它停止了。
在我的Cargo.toml中,我具有以下依赖性:

[dependencies]
ssh2 = "0.8"
它取决于libssh2。
代码更加复杂,但是我设法用这个肮脏的代码重现了这个问题:
  use std::fs::File;
use std::io::Read;
use std::io::Write;
#[allow(unused_imports)]
use std::io::Error;
use std::net::TcpStream;
use ssh2::Session;
use std::path::Path;
use std::io::prelude::*;

fn main() {
println!("Parto!");

let tcp = TcpStream::connect("myhost:22").unwrap();
let mut sess = Session::new().unwrap();
sess.set_tcp_stream(tcp);
sess.handshake().unwrap();
sess.userauth_password("user", "password").unwrap();
assert!(sess.authenticated());

let (mut remote_file, stat) = sess.scp_recv(Path::new("/home/pi/dbeaver.exe")).unwrap();
println!("remote file size: {}", stat.size());
let mut buf: Vec<u8> = vec![0;1000];

loop {
let read_bytes = remote_file.read(&mut buf).unwrap();
println!("Read bytes: {}.", read_bytes);
if read_bytes < 1000 {
break;
}
} //ending loop
}
我在Windows 10和Linux Debian上都进行了测试。当文件读取的内容多于几个KB时,问题始终存在:
let read_bytes = remote_file.read(&mut buf).unwrap();
读取的数据小于缓冲区大小(但文件未结束)。
已对二进制文件或asci文件进行了测试。
没有错误,它只是停止阅读。奇怪的是:它有时会停止在8 MB,有时会停止在16 KB。使用相同的文件和主机...
我需要在哪里挖掘或需要检查什么?

最佳答案

从文档中引用io::Read特性(由ssh2实现):

It is not an error if the returned value n is smaller than the buffer size, even when the reader is not at the end of the stream yet. This may happen for example because fewer bytes are actually available right now (e. g. being close to end-of-file) or because read() was interrupted by a signal.


由于您正在远程阅读,这可能仅意味着剩余字节仍在网络中传输,并且在目标计算机上尚不可用。
如果确定有足够的传入数据来填充缓冲区,则可以使用 read_exact ,但是请注意,如果可用数据短于缓冲区,则会返回错误。
编辑:或者甚至更好,使用 read_to_end ,它不需要事先知道大小(我不知道为什么我昨天在写原始答案时看不到它的大小)。

关于rust - Libssh2停止读取大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64433067/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com