Beginner: Reading TcpStream messages

I have only just been learning rust and quite enjoying it. Currently i have been putting together a type of proxy server however i can simplify this to a simple echo server.

What i find is that if messages were written to the socket faster than it has been read then they get appended to the read stream.

For Example:

The following will print “TestTest” but i would like to segregate the messages into their sent pieces “Test” and “Test”.

Is there a way to do this without needing to add extra bytes at the end of the message to split the text on? My goal is not to append to the proxy’ed buffer and add extra checks for splits etc.

Client

    stream.write(&hello.as_bytes());
    stream.write(&hello.as_bytes());

Server

  match stream.read(&mut buf) {
        Ok(received_size) => {
            if received_size == 0 {
                println!("Connection closed");
                break;
            }

            let result = std::str::from_utf8(&buf[..received_size]).expect("Conversion");
            println!("Received: {}", &result);

        },
        Err(err) => {
            println!("There was an error {:?}", err);
            break;
        },
    }

TCP is a streaming protocol - you need to frame messages yourself.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.