-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
tungstenite_socket.rs
71 lines (64 loc) · 2.37 KB
/
tungstenite_socket.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use futures::{sink::SinkExt, stream::StreamExt};
use tokio::{
net::TcpStream,
sync::mpsc::{channel, Receiver, Sender},
};
use tokio_tungstenite::{
tungstenite::{Error as SocketError, Message as WebSocketMessage},
MaybeTlsStream, WebSocketStream,
};
use super::*;
type WebSocket = WebSocketStream<MaybeTlsStream<TcpStream>>;
impl From<Message> for WebSocketMessage {
fn from(value: Message) -> Self {
match value {
Message::Binary(data) => WebSocketMessage::Binary(data),
Message::Close => WebSocketMessage::Close(None),
Message::Ping => WebSocketMessage::Ping(vec![]),
}
}
}
pub fn tungstenite_socket_connector(socket: WebSocket, workspace_id: &str) -> (Sender<Message>, Receiver<Vec<u8>>) {
let (mut socket_tx, mut socket_rx) = socket.split();
// send to remote pipeline
let (local_sender, mut local_receiver) = channel::<Message>(100);
{
// socket send thread
let workspace_id = workspace_id.to_owned();
tokio::spawn(async move {
let mut retry = 5;
while let Some(msg) = local_receiver.recv().await {
if let Err(e) = socket_tx.send(msg.into()).await {
let error = e.to_string();
if matches!(e, SocketError::ConnectionClosed | SocketError::AlreadyClosed) || retry == 0 {
break;
} else {
retry -= 1;
error!("socket send error: {}", error);
}
} else {
retry = 5;
}
}
info!("socket send final: {}", workspace_id);
});
}
let (remote_sender, remote_receiver) = channel::<Vec<u8>>(512);
{
// socket recv thread
let workspace_id = workspace_id.to_owned();
tokio::spawn(async move {
while let Some(msg) = socket_rx.next().await {
if let Ok(WebSocketMessage::Binary(binary)) = msg {
trace!("recv from remote: {}bytes", binary.len());
if remote_sender.send(binary).await.is_err() {
// pipeline was closed
break;
}
}
}
info!("socket recv final: {}", workspace_id);
});
}
(local_sender, remote_receiver)
}