60 lines
1.8 KiB
Rust
60 lines
1.8 KiB
Rust
use openssl::ssl::{SslConnector, SslMethod};
|
|
use std::io::{ErrorKind, Write};
|
|
use std::net::TcpStream;
|
|
use std::sync::mpsc;
|
|
use std::thread;
|
|
use std::time::Duration;
|
|
|
|
pub fn write_to_server(
|
|
tcp_stream: TcpStream,
|
|
server: String,
|
|
rx: mpsc::Receiver<String>,
|
|
tx: mpsc::Sender<String>,
|
|
) {
|
|
let connector = SslConnector::builder(SslMethod::tls()).unwrap().build();
|
|
let mut stream = connector
|
|
.connect(&server, tcp_stream)
|
|
.expect("Couldn't start TLS");
|
|
|
|
stream
|
|
.get_mut()
|
|
.set_nonblocking(true)
|
|
.expect("Failed to set nonblocking");
|
|
|
|
loop {
|
|
let mut buffer: Vec<u8> = Vec::new();
|
|
let mut buf: [u8; 1] = [0];
|
|
let newline: u8 = b'\n';
|
|
|
|
while buf[0] != newline {
|
|
match stream.ssl_read(&mut buf) {
|
|
Ok(_length) => {
|
|
if _length > 0 {
|
|
buffer.push(buf[0]);
|
|
}
|
|
}
|
|
Err(_error) => match _error.io_error() {
|
|
None => {
|
|
dbg!(_error);
|
|
}
|
|
Some(error) => match error.kind() {
|
|
ErrorKind::WouldBlock => {}
|
|
_ => {
|
|
dbg!(error.kind());
|
|
println!("Couldn't read the stream");
|
|
}
|
|
},
|
|
},
|
|
}
|
|
let value = rx.try_recv().unwrap_or("".to_string());
|
|
match stream.write_all(value.as_bytes()) {
|
|
Ok(_) => {}
|
|
Err(_e) => println!("Couldn't send {value}"),
|
|
};
|
|
}
|
|
|
|
let _ = tx.send(dbg!(String::from_utf8_lossy(&buffer).to_string()));
|
|
thread::sleep(Duration::from_millis(100));
|
|
}
|
|
}
|