Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created May 21, 2022 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/d52e5de95efe63d43ba7b7a8d45b4c1e to your computer and use it in GitHub Desktop.
Save rust-play/d52e5de95efe63d43ba7b7a8d45b4c1e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
pub fn run<'de, T: Deserialize<'de>, Callback: Fn(T)>(&self, callback: Callback) -> Result<()> {
let req = Url::parse(&self.uri).unwrap();
let (mut ws, _) = connect(req).expect("Can't connect");
loop {
if let Ok(msg) = ws.read_message() {
match msg {
Message::Binary(_) => {}
Message::Close(_) => break,
Message::Ping(_) => {}
Message::Pong(_) => {}
Message::Text(content) => {
println!("raw msg: {}", content);
// 这里为什么要使用泛型 T 呢?
// 因为根据 WebSocket 连接的 uri 不同,接收到的消息是不同的。
// 在我的项目中,有 3 个不同的 uri,每个 uri 连接返回的消息我已封装成了一个 Enum。
// 所以我预期的用户调用这个 run 方法的方式是:
// 连接 uri1: client.run(|response: ResponseEnum1| { match response })
// 连接 uri2: client.run(|response: ResponseEnum2| { match response })
// 连接 uri3: client.run(|response: ResponseEnum3| { match response })
match serde_json::from_str::<T>(&self.content) {
Ok(res) => callback(res),
Err(e) => {
println!("Error: {}", e)
}
}
}
}
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment