I'm trying to build a simple client crate for a program that has it's own simple TCP protocol.
Most of the communication works by sending a command and immediately reading a single line response. Some of the commands need to read multiple responses. I've been using BufReader::read_line()
to read single lines but this seems to fall down when it reads too much, the second read_line()
can be missing the start of the line.
My assumption is that I'm meant to be keeping the BufReader
around so that it keeps its internal state.
I'm doing this by passing a reference of the TcpStream
to the BufReader
and BufWriter
but I'm getting “borrowed value does not live long enough”. My question is; where do I “store” the TcpStream
so that it does live long enough?
I've tried different iterations of trying to store the stream
on the Connection
struct but I can't seem to get it to work.
Here is a cut down version of the code:
use std::io::{self, BufReader, BufWriter};
use std::net::TcpStream;
#[derive(Debug)]
pub struct Connection<'a> {
reader: BufReader<&'a TcpStream>,
writer: BufWriter<&'a TcpStream>,
}
impl<'a> Connection<'a> {
pub fn new(stream: TcpStream) -> io::Result<Self> {
let connection = Self {
reader: BufReader::new(&stream),
writer: BufWriter::new(&stream),
};
Ok(connection)
}
}
pub struct Search<'a> {
connection: Connection<'a>,
}
impl<'a> Search<'a> {
// fn new(stream: &'a TcpStream) -> Self {
fn new() -> Self {
let stream = TcpStream::connect("127.0.0.1:100").unwrap();
let connection = Connection::new(stream).unwrap();
Self { connection }
}
}
fn main() {
// let stream = TcpStream::connect("127.0.0.1:100").unwrap();
// Search::new(&stream);
Search::new();
}
If I uncomment the commented-out lines it works.