Make writes actually work

This commit is contained in:
Yash Karandikar 2021-11-03 11:15:26 -05:00
parent 91a7db6c48
commit c23e0b7bdf
2 changed files with 18 additions and 28 deletions

View file

@ -5,7 +5,6 @@ use std::net::TcpStream;
pub struct Client {
stream: TcpStream,
config: Config,
pub has_identified: bool,
}
pub struct Config {
@ -43,25 +42,18 @@ impl Client {
pub fn new(host: &str, port: u16, config: Config) -> Result<Self, Error> {
let stream = TcpStream::connect(format!("{}:{}", host, port))?;
Ok(Self {
stream,
config,
has_identified: false,
})
Ok(Self { stream, config })
}
pub fn try_identify(&mut self) -> Result<(), Error> {
if !self.has_identified {
self.write_command(Command::CAP(CapMode::LS))?;
self.write_command(Command::USER(
self.config.username.clone(),
"*".into(),
"*".into(),
self.config.username.clone(),
))?;
self.write_command(Command::NICK(self.config.nickname.clone()))?;
self.write_command(Command::CAP(CapMode::END))?;
}
pub fn identify(&mut self) -> Result<(), Error> {
self.write_command(Command::CAP(CapMode::END))?;
self.write_command(Command::USER(
self.config.username.clone(),
"*".into(),
"*".into(),
self.config.username.clone(),
))?;
self.write_command(Command::NICK(self.config.nickname.clone()))?;
Ok(())
}
@ -72,11 +64,7 @@ impl Client {
match self.stream.read(&mut buffer) {
Ok(_) => {}
Err(e) => {
println!("error occured {}", e);
return None;
}
Err(_) => return None,
};
Some(String::from_utf8_lossy(&buffer).into())
@ -91,9 +79,12 @@ impl Client {
}
fn write(&mut self, data: &str) -> Result<(), Error> {
let bytes = self.stream.write(data.as_bytes())?;
println!("Wrote {} bytes", bytes);
// self.stream.flush()?;
let formatted = {
let new = format!("{}\n", data);
Cow::Owned(new) as Cow<str>
};
self.stream.write(formatted.as_bytes())?;
Ok(())
}

View file

@ -13,10 +13,9 @@ fn main() -> Result<(), std::io::Error> {
let config = Config::new("test", Some("test"), Some("+B"));
let mut client =
Client::new("192.168.1.28", 6667, config).expect("Unable to connect to IRC server");
client.identify()?;
loop {
client.try_identify()?;
// client.has_identified = true;
if let Some(line) = client.read_string() {
print!("{}", line);
}