I have a websoket connection, and I hope other processes will actively send messages to the server, but rust can't get the sending object in the global variable at all
websocket.rs
use std::{sync::{Mutex}};
use tungstenite::{connect, Message};
use crate::store::global_store::WEBS_IPC;
pub static WEBS_IPC: OnceCell<Mutex<WebSocket<MaybeTlsStream<TcpStream>>>> = OnceCell::new();
/**
* init websocket
*/
pub async fn init_websocket () {
// 连地址
let url = url::Url::parse("ws://myhost.com").unwrap();
let ( socket, response) =connect(url).expect("Can't connect");
WEBS_IPC.set(Mutex::new(socket));
tokio::spawn(handle_connection());
}
pub async fn handle_connection () {
let socket = WEBS_IPC.get().unwrap();
loop {
let mut c = socket.lock().unwrap();
let msg = c.read_message().expect("Error reading message");
println!("Received: {}", msg);
}
}
#[tokio::main]
pub async fn send_msg (msg:String) {
let socket = WEBS_IPC.get().unwrap();
let mut c = socket.lock().unwrap();
c.write_message(Message::Text("Hello WebSocket".into())).unwrap();
}
msg_send.rs
// init websocket
init_websocket().await;
// send msg
send_msg("test".to_string());
But reading the server message in this way has been blocking the lock, unable to send the message, I'm going crazy!