core/src/chat/serv_conn.rs

57 lines
1.9 KiB
Rust
Raw Normal View History

2021-02-27 21:58:55 +00:00
use super::serv_handler::to_server_sender;
use crate::chat::types::{PackedMessage, RP, SP};
2021-01-06 09:41:33 +00:00
use async_std::task;
2021-01-06 04:18:46 +00:00
use serde_derive::Deserialize;
use std::env;
2021-01-06 09:41:33 +00:00
use tokio::{
2021-02-27 21:58:55 +00:00
io::{self, AsyncReadExt},
net::{tcp::OwnedReadHalf, TcpStream},
2021-01-06 09:41:33 +00:00
};
2021-01-06 04:18:46 +00:00
2021-01-06 09:41:33 +00:00
#[tokio::main]
2021-01-09 14:03:00 +00:00
pub async fn listen_server(client_sender: SP, server_receiver: RP) -> io::Result<()> {
task::block_on(connect_to_server(client_sender, server_receiver))
2021-01-06 04:18:46 +00:00
}
2021-01-09 14:03:00 +00:00
async fn connect_to_server(client_sender: SP, server_receiver: RP) -> io::Result<()> {
2021-01-06 04:18:46 +00:00
let addr = env::args()
.nth(1)
.unwrap_or_else(|| "127.0.0.1:9481".to_string());
2021-03-27 06:09:59 +00:00
let sr = client_sender.clone();
2021-04-05 16:39:36 +00:00
let stream = TcpStream::connect(&addr).await.expect("Unable to connect to FCP");
let (receiver, sender) = stream.into_split();
log::info!("Connected to FCP");
2021-01-09 14:03:00 +00:00
let t = task::spawn(server_responce_getter(receiver, client_sender));
to_server_sender(sender, server_receiver, sr).await?;
2021-01-09 14:03:00 +00:00
match t.await {
Ok(_) => Ok(()),
Err(e) => Err(e),
2021-01-09 14:03:00 +00:00
}
}
async fn server_responce_getter(mut receiver: OwnedReadHalf, client_sender: SP) -> io::Result<()> {
loop {
2021-03-31 04:12:26 +00:00
// each freenet responce have an identifier and program will define what to do with request by this identifier
//TODO create handle_fcp_response function
2021-03-27 06:09:59 +00:00
let mut buffer = [0; 1024];
2021-01-06 09:41:33 +00:00
match receiver.read(&mut buffer).await {
2021-01-09 14:03:00 +00:00
Ok(_) => {
2021-01-06 09:41:33 +00:00
let received = String::from_utf8_lossy(&buffer[..]);
client_sender
2021-03-27 06:09:59 +00:00
.send(PackedMessage::FromFreenet(received.to_string()))
2021-03-24 07:32:31 +00:00
.expect("Falied to send message to client thread");
log::info!("Sended to client!");
2021-01-06 09:41:33 +00:00
}
2021-03-24 07:32:31 +00:00
Err(e) => log::error!("Error: {} ", e),
2021-01-06 09:41:33 +00:00
}
}
2021-01-06 04:18:46 +00:00
}
#[derive(Deserialize, Debug)]
struct FrontMsg {
2021-01-09 14:03:00 +00:00
user_id: u32,
receiver_id: u32,
2021-01-06 04:18:46 +00:00
message: String,
time: String,
}