use std::io::{self, BufRead, BufReader}; use std::net::TcpStream; use std::io::{Read,…
- User
use std::io::{self, BufRead, BufReader}; use std::net::TcpStream; use std::io::{Read, Write};
pub struct XmppConnection { stream: TcpStream, reader: BufReader, }
pub struct Properties<'a> { pub server_address: &'a str, pub room_jid: &'a str, pub room_nick: &'a str, pub room_pass: Option<&'a str>, pub acc_jid: &'a str, pub acc_pass: &'a str, }
impl<'a> Properties<'a> { pub fn new( server_address: &'a str, room_jid: &'a str, room_nick: &'a str, room_pass: Option<&'a str>, acc_jid: &'a str, acc_pass: &'a str, ) -> Self { Properties { server_address, room_jid, room_nick, room_pass, acc_jid, acc_pass, } } }
impl XmppConnection { pub fn new(properties: &Properties) -> Result<Self, Box> { let stream = TcpStream::connect(properties.server_address)?; let reader = BufReader::new(stream.try_clone()?);
codeOk(XmppConnection { stream, reader }) } pub fn read_xml(&mut self) -> Result<String, std::io::Error> { let mut buffer = [0; 4096]; let size = self.reader.read(&mut buffer)?; Ok(String::from_utf8_lossy(&buffer[..size]).to_string()) } pub fn send_xml(&mut self, xml: &str) -> Result<(), std::io::Error> { self.stream.write_all(xml.as_bytes())?; Ok(()) } pub fn send_message(&mut self, properties: &Properties, message: &str) -> Result<(), Box<dyn std::error::Error>> { let xml = format!( "<message from=\"{}\" to=\"{}\" type=\"chat\"> <body>{}</body> </message>", properties.room_jid, properties.acc_jid, message ); self.send_xml(&xml)?; Ok(()) } pub fn handle_input(&mut self) -> Result<(), Box<dyn std::error::Error>> { let mut reader = BufReader::new(io::stdin()); let mut input = String::new(); loop { input.clear(); reader.read_line(&mut input)?; // Remove trailing newline input = input.trim().to_string(); if input.is_empty() { continue; } self.send_message(&input)?; let response = self.read_xml()?; println!("Received: {}", response); } } - Assistant
Yes, you can concatenate the
Propertiesstruct with theXmppConnectionstruct by adding apropertiesfield to theXmppConnectionstruct. Here's an example:rust