rust - Trouble reading from TcpStream -
i'm attempting implement haskell irc bot tutorial in rust , having difficulty reading server sends me after connecting. seems happen connect, read ~5 kb server, , 240 seconds later dumped @ once instead of being read line-by-line when ping timeout closes connection (which should happen eventually, since don't yet have ping-pong function reply with). here's have far:
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(); } }
but when modifiy loop bit using array instead of string, output expect:
let mut line; loop { line = [0; 512]; let result = stream.read(&mut line); match result { ok(n) => println!("received {} bytes",n), _ => {}, } }
so conclusion stream.read_to_string(&mut line)
somehow culprit. know why might case, or there obvious i'm overlooking?
note: i'm using 1.0 stable release
edit: more specific, in first case output appears after ping timeout, upon following printed:
//around 4 minutes elapse before printed console received 5323 bytes received 0 bytes received 0 bytes received 0 bytes //continues print "received 0 bytes" since connection has closed haven't broken out of infinite loop
in second case using array, receive correct output immediately:
received 64 bytes received 51 bytes received 512 bytes received 512 bytes received 350 bytes received 512 bytes received 512 bytes ...
check out docs read_to_string
:
read bytes until eof in source, placing them buf.
(emphasis mine)
notably, aren't reading 512 bytes in first example, pre-allocating 512 bytes of space , reading every byte until socket closes - 4 minutes later.
it sounds want use bufread::read_line
:
read bytes until newline byte (the 0xa byte) reached, , append them provided buffer.
this function continue read (and buffer) bytes underlying stream until newline delimiter (the 0xa byte) or eof found. once found, bytes to, , including, delimiter (if found) appended buf.
Comments
Post a Comment