Connecting two websockets together #2881
Unanswered
astrale-sharp
asked this question in
Questions
Replies: 1 comment 1 reply
-
One major point here - I don't see how you could get your hands on both sides at the same time, since they would come in with different requests. One simple option would be to convert them both to channels, and use a managed object to get a pair of One option, that connects pairs of websockets, simply in the order they arrive: struct Connector {
pair: Mutex<
Option<(
tokio::sync::mpsc::Sender<Message>,
tokio::sync::mpsc::Receiver<Message>,
)>,
>,
}
#[get("/connect")]
fn connect(ws: WebSocket, conn: &State<Connector>) -> Channel<'static> {
let mut lock = conn.pair.lock().unwrap();
let (send, mut recv) = if let Some((send, recv)) = lock.take() {
(send, recv)
} else {
let (send_tx, send_rx) = tokio::sync::mpsc::channel(2);
let (recv_tx, recv_rx) = tokio::sync::mpsc::channel(2);
*lock = Some((send_tx, recv_rx));
(recv_tx, send_rx)
};
ws.channel(move |mut ws| {
Box::pin(async move {
loop {
select! {
msg = ws.next() => match msg {
Some(msg) => send.send(msg?).await.map_err(|_| Error::AlreadyClosed)?,
None => return Ok(()),
},
msg = recv.recv() => match msg {
Some(msg) => ws.send(msg).await?,
None => return Ok(()),
},
}
}
})
})
} Your use-case likely requires more complex logic for deciding which pairs of websockets to connect, but the general pattern (the channel code, and either creating and storing, or taking a previously stored pair of channels) should still apply. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi there, I want to connect two clients websockets together but I am unsure if it's possible given that rocket_ws::WebSocket doesn't implement Clone.
for simplicity imagine this function signature :
if we wanted to create a stream that sends ws messages to ws2 we would have consumed both of them, so we can't have a stream in the other direction
we could have two websockets per client but that seems akward
Am I missing something? Do you have any pointers?
Thanks
Beta Was this translation helpful? Give feedback.
All reactions