我正在尝试实施Haskell IRC 机器人教程 https://wiki.haskell.org/Roll_your_own_IRC_bot在 Rust 中,我在阅读连接后服务器发送给我的内容时遇到一些困难。似乎发生的情况是,我连接并从服务器读取约 5 KB 的内容,然后大约 240 秒后,所有内容都会立即转储,而不是逐行读取。连接因 ping 超时而关闭,这最终应该发生,因为我还没有可以回复的 ping-pong 函数。
这是我到目前为止所拥有的:
use std::io::{Read, Write};
use std::net::TcpStream;
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();
}
}
当我修改循环 a 以使用数组而不是字符串时,我立即得到我期望的输出:
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)
某种程度上是罪魁祸首。为什么会这样呢?有什么明显的事情是我忽略的吗?
更具体地说,在第一种情况下,输出会在 ping 超时后出现,并打印以下内容:
//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
...