So I’m on the newish side to rust and I’m right now trying to have parallel reading and writing with a websocket. I’m spawning this to listen to connections
tokio::spawn(async move {
println!("Spawning a worker");
loop {
let message: Message = {
let mut locked_socket: MutexGuard<UnifiedWebSocket> = socket.lock().unwrap();
match locked_socket.read() {
Ok(msg: Message) => msg,
Err(e: Error) => {
eprintln!("Error reading message: {}", e);
break;
}
}
};
match message {
Message::Binary(bin: Vec<u8>) => {
println!("{:?}", bin);
println!("Received a message on websocket");
}
_ => continue
}
}
});
Which means that the socket’s MutexGuard is constantly locked in a loop.
This means that this part of code that’s supposed to write using the socket will stop on the lock step, waiting for the socket to unlock, which will never happen, due to it running in a loop in the snipped above.
#[post("/", format="text", data = "<input>")]
fn my_endpoint(state: &rocket::State<MySharedState>, input: String) -> Status {
println!("my_endpoint Received a message on endpoint");
let socket:&mut UnifiedWebSocket = &mut *state.inner().socket.lock().unwrap();
At leas that’s what I’m suspecting is happening.
So, as I said I’m pretty new to rust in general so I’m not even sure if I’ve correctly identified the problem and maybe I should handle the socket in different way, any help would be greatly appreciated.
I should also clarify that the UnifiedWebSocket is my shot at unifying the “server” and “client” websocket types with one enum.
enum UnifiedWebSocket {
Plain(WebSocket<TcpStream>),
Tls(WebSocket<MaybeTlsStream<TcpStream>>),
}
impl UnifiedWebSocket {
fn send(&mut self, message: Message) -> Result<(), tungstenite::Error> {
match self {
UnifiedWebSocket::Plain(socket) => socket.send(message),
UnifiedWebSocket::Tls(socket) => socket.send(message),
}
}
fn read(&mut self) -> Result<Message, tungstenite::Error> {
match self {
UnifiedWebSocket::Plain(socket) => socket.read(),
UnifiedWebSocket::Tls(socket) => socket.read(),
}
}
}
Cheers
SmigorX is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.