Created
December 30, 2019 23:42
-
-
Save mcbridejc/511b7c1c2b64b1ff81006e4db92f3284 to your computer and use it in GitHub Desktop.
Simple rust web socket broadcaster example with ws-rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "rssocket" | |
version = "0.1.0" | |
edition = "2018" | |
[dependencies] | |
anyhow = "*" | |
env_logger = "*" | |
ws = "*" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub mod broadcaster { | |
use anyhow::Result; | |
use std::sync::mpsc::{channel, Sender}; | |
use std::thread; | |
use ws; | |
struct Server { | |
} | |
impl ws::Handler for Server { | |
fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> { | |
// Do whatever with incoming message; this is intended to be broadcast only | |
println!("Got message: {}", msg); | |
Ok(()) | |
} | |
} | |
pub struct Broadcaster { | |
msg_in: Sender<String>, | |
//msg_out: Receiver<String>, | |
} | |
impl Broadcaster { | |
pub fn new(host: &'static str) -> ws::Result<Broadcaster> { | |
let ws = ws::WebSocket::new(|_| { Server{} } )?; | |
let bcast = ws.broadcaster(); | |
let (msg_in, msg_out) = channel(); | |
thread::spawn(move || { | |
loop { | |
let msg = msg_out.recv().unwrap(); | |
bcast.send(msg).expect("Error sending message"); | |
} | |
}); | |
thread::spawn(move || { | |
ws.listen(host).unwrap(); | |
}); | |
Ok(Broadcaster{msg_in}) | |
} | |
pub fn broadcast(&self, msg: String) -> Result<()> { | |
Ok(self.msg_in.send(msg)?) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::thread::sleep; | |
use std::time; | |
use rssocket::broadcaster::Broadcaster; | |
fn main() { | |
env_logger::init(); | |
let bcast = Broadcaster::new("127.0.0.1:2100").unwrap(); | |
loop { | |
println!("Broadcasting..."); | |
bcast.broadcast("No thank you".to_string()).unwrap(); | |
sleep(time::Duration::from_millis(1000)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment