我試圖在Rust中實現Haskell IRC bot tutorial,並且在連接後讀取服務器發送的內容時遇到了一些困難。看起來發生的是我連接,從服務器讀取〜5 kb,然後大約240秒後,所有內容都立即轉儲,而不是在ping超時關閉連接時逐行讀取(最終會發生這種情況,因爲我還沒有乒乓功能來回復)。這是我到目前爲止有:從TcpStream讀取時遇到問題
use std::net::TcpStream;
use std::io::Read;
use std::io::Write;
fn main() {
let mut stream = TcpStream::connect("irc.freenode.org:6667").unwrap();
let _ = stream.write(b"NICK G-SERUFU\r\n");
let _ = stream.write(b"USER G-SERUFU 0 * :brobot\r\n");
let _ = stream.write(b"JOIN #tutbot-testing\r\n");
let mut line = String::with_capacity(512);
loop {
let result = stream.read_to_string(&mut line);
match result {
Ok(n) => println!("Received {} bytes",n),
_ => {},
}
line.clear();
}
}
但是當我通過使用數組而不是字符串modifiy循環了一下,我立即得到輸出我想到:
let mut line;
loop {
line = [0; 512];
let result = stream.read(&mut line);
match result {
Ok(n) => println!("Received {} bytes",n),
_ => {},
}
}
所以我的結論是那stream.read_to_string(&mut line)
是不知何故的罪魁禍首。有沒有人知道爲什麼可能是這種情況,或者有什麼明顯的我忽略?
注:我使用的1.0的穩定版本
編輯:更具體地,在第一種情況下的輸出的平超時之後出現,在其下面的印刷:
//Around 4 minutes elapse before anything is printed to console
Received 5323 bytes
Received 0 bytes
Received 0 bytes
Received 0 bytes
//Continues to print "Received 0 bytes" since the connection has closed but I haven't broken out of the infinite loop
在第二種情況下使用陣列時,收到正確的輸出幾乎立即:
Received 64 bytes
Received 51 bytes
Received 512 bytes
Received 512 bytes
Received 350 bytes
Received 512 bytes
Received 512 bytes
...
請詳細描述兩種情況下會發生什麼情況。這個問題可能與'stream.read'重載對於字符串和數組的不同方式有關。在字符串的情況下,它可以在返回之前等待512字節,而對於數組,它將立即返回,即使收到較少。很可能這不是真的(會是奇怪的邏輯),但你有這個想法 –