feat: works

This commit is contained in:
2021-07-03 18:55:49 +08:00
parent b717c864ac
commit cd8afe953c
3 changed files with 202 additions and 16 deletions

View File

@@ -10,6 +10,7 @@ use tokio::sync::mpsc::channel;
use url::Url;
use rustyline::Editor;
use rustyline::error::ReadlineError;
use std::time::Duration;
#[tokio::main]
async fn main() {
@@ -25,6 +26,7 @@ async fn main() {
failure_and_exit!("Parse connect url: {}, failed: {}", connect, e);
});
debugging!("Connecting to: {}", url);
let r = connect_to_and_loop(&url).await;
match r {
Ok(_) => success!("Success"),
@@ -48,31 +50,53 @@ async fn connect_to_and_loop(url: &Url) -> XResult<()> {
}
});
let t = std::thread::spawn(|| {
let rt = tokio::runtime::Runtime::new().unwrap();
let cloned_sender = sender.clone();
let _t = std::thread::spawn(move || {
let mut rl = Editor::<()>::new();
loop {
let readline = rl.readline("ws $ ");
match readline {
Ok(line) => {
rl.add_history_entry(line.as_str());
println!("Input line: {}", line);
},
if !line.is_empty() {
rl.add_history_entry(line.as_str());
println!("Input line: {}", line);
let cloned_sender = cloned_sender.clone();
rt.spawn(async move {
if let Err(e) = cloned_sender.send(Message::Text(line)).await {
failure!("Send message failed: {}", e);
}
});
}
}
Err(ReadlineError::Interrupted) => {
println!("CTRL-C");
break
},
information!("Press Ctrl+C");
std::process::exit(1);
}
Err(ReadlineError::Eof) => {
println!("CTRL-D");
break
},
break;
}
Err(err) => {
println!("Error: {:?}", err);
break
break;
}
}
}
});
let time_cloned_sender = sender.clone();
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
debugging!("Send ping message");
if let Err(e) = time_cloned_sender.send(Message::Ping(vec![])).await {
debugging!("Send ping message failed: {}", e);
return;
}
}
});
loop {
let next = ws_read.next().await;
match next {
@@ -86,12 +110,12 @@ async fn connect_to_and_loop(url: &Url) -> XResult<()> {
Some(Ok(message)) => {
match message {
Message::Ping(msg) => {
information!("Received ping message: {:?}", msg);
debugging!("Received ping message: {:?}", msg);
let r = sender.send(Message::Pong(msg)).await;
r.ok();
}
Message::Pong(msg) => {
information!("Received pong message: {:?}", msg);
debugging!("Received pong message: {:?}", msg);
}
Message::Close(close_frame) => {
information!("WebSocket closed: {:?}", close_frame);
@@ -107,6 +131,6 @@ async fn connect_to_and_loop(url: &Url) -> XResult<()> {
}
}
t.join().unwrap();
Ok(())
// t.join().unwrap();
// Ok(())
}