-2

I am looking at this tokio example that connects to a tcp server:

use tokio::io::Interest;
use tokio::net::TcpStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let stream = TcpStream::connect("127.0.0.1:8080").await?;

    loop {
        let ready = stream.ready(Interest::READABLE | Interest::WRITABLE).await?;

        if ready.is_readable() {
            let mut data = vec![0; 1024];
            // Try to read data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match stream.try_read(&mut data) {
                Ok(n) => {
                    println!("read {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
    }

I successfully connect but this simply returns the # of bytes that were read. How can I println! the bytes read after converting it to a string?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • 2
    Does this answer your question? [How do I convert a Vector of bytes (u8) to a string?](https://stackoverflow.com/questions/19076719/how-do-i-convert-a-vector-of-bytes-u8-to-a-string) – Colonel Thirty Two Sep 27 '22 at 17:07

1 Answers1

1

You're streaming the data from the TCP connection into your buffer data you made:

let mut data = vec![0; 1024];

In order to now convert the buffered raw data into a String, try using the function

let data_string = String::from_utf8_lossy(data);
IonImpulse
  • 156
  • 6