Converting TCP byte data to a string

So, I’m trying to connect to an IRC channel using TCP which seems to be working. But now I want to print the data received. I can make it print “Received {x} bytes”, and I can see that I do receive data from the IRC. But I just don’t know how to read it. This is what I have so far:

use std::io::{Read, Write};
use std::net::TcpStream;

fn main() {
    let mut socket = TcpStream::connect("irc.chat.twitch.tv:6667").unwrap();

    let result_auth = socket.write(b"PASS oauth:somelongtokenhere\r\n");
    println!("{:?}", result_auth);

    let result_nick = socket.write(b"NICK botname\r\n");
    println!("{:?}", result_nick);

    let result_chan = socket.write(b"JOIN #channel-to-join\r\n");
    println!("{:?}", result_chan);

    let mut line;
    loop {
        line = [0u8; 1024];
        let result = socket.read(&mut line);
        match result {
            Ok(n) => println!("Received {} bytes", n),
            _ => {},
        }
    }
}

How would I read each line received and print it?

println!("{:?}", &line[0..n]);

Oh sorry, I was a bit unclear. I want to read it in normal text. I don’t want to read the bytes as strings, I want to turn the bytes into a string.

Try from_utf8 as a starting point. Could want something else to deal with buffer not being utf8 or end character split.

alternatively from_utf8_lossy if you want it to ignore invalid utf8 characters

you might also want to use write_all instead of write, as the latter will only do one try to write, which could be partial

You could also wrap your TcpStream in a BufReader, and then read each line with the lines iterator from the BufRead trait:

use std::io::{Write, BufReader, BufRead};
use std::net::TcpStream;

fn main() {
    let mut socket = TcpStream::connect("irc.chat.twitch.tv:6667").unwrap();

    let result_auth = socket.write(b"PASS oauth:somelongtokenhere\r\n");
    println!("{:?}", result_auth);

    let result_nick = socket.write(b"NICK botname\r\n");
    println!("{:?}", result_nick);

    let result_chan = socket.write(b"JOIN #channel-to-join\r\n");
    println!("{:?}", result_chan);

    let buffered = BufReader::new(socket);

    for res in buffered.lines() {
        match res {
            Ok(line) => println!("Received line: {}", line),
            _ => {},
        }
    }
}

Hi,
just to add, there is already a crate for IRC that probably has most/all of what you need:

https://crates.io/crates/irc

If all you want is creating an IRC bot or some other kind of client, using the crate is going to be a lot easier than reimplementing everything for your project. On the other hand, if you’re in for the challenge of doing everything manually, don’t mind me and have fun :slight_smile: