60 lines
1.8 KiB
Rust
60 lines
1.8 KiB
Rust
use futures_util::stream::{SplitSink, SplitStream};
|
|
use futures_util::StreamExt;
|
|
use iced::subscription::{Subscription, channel};
|
|
use tokio::net::TcpStream;
|
|
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
|
|
use crate::events::ChatAppEvent;
|
|
|
|
#[derive(Debug)]
|
|
pub enum AppWebsocketState {
|
|
Disconnected,
|
|
Error(String),
|
|
Connected(SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, tokio_tungstenite::tungstenite::Message>, SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>)
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct AppWebsocketConfig {
|
|
host: String,
|
|
user: Option<String>,
|
|
pass: Option<String>
|
|
}
|
|
|
|
impl AppWebsocketConfig {
|
|
pub fn new(host: String, user: Option<String>, pass: Option<String>) -> Self {
|
|
Self {
|
|
host,
|
|
user,
|
|
pass
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn websocket(config: AppWebsocketConfig) -> Subscription<ChatAppEvent> {
|
|
struct Websocket;
|
|
|
|
channel(
|
|
std::any::TypeId::of::<Websocket>(),
|
|
100,
|
|
|mut output| async move {
|
|
let mut state = AppWebsocketState::Disconnected;
|
|
|
|
loop {
|
|
match &state {
|
|
AppWebsocketState::Disconnected => {
|
|
match connect_async(&config.host).await {
|
|
Ok((conn, res)) => {
|
|
let (ws_recv, ws_send) = conn.split();
|
|
state = AppWebsocketState::Connected(ws_recv, ws_send);
|
|
},
|
|
Err(err) => {
|
|
state = AppWebsocketState::Error(err.to_string());
|
|
}
|
|
}
|
|
}
|
|
AppWebsocketState::Connected(ws_recv, ws_send) => {}
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
)
|
|
}
|