Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 16, 2019 19:49
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/9fc4399d3cccec2a72eed0c858e60e5e to your computer and use it in GitHub Desktop.
Save rust-play/9fc4399d3cccec2a72eed0c858e60e5e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::sync::Arc;
use tokio::prelude::*;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
struct Message {
buf: Vec<u8>,
}
pub struct PubSubSocket {
socket: TcpStream,
tx_sender: mpsc::UnboundedSender<Message>,
tx_receiver: mpsc::UnboundedReceiver<Message>,
}
impl PubSubSocket {
// TODO: make channel bounded in size (needs to be configurable)
pub fn new(socket: TcpStream) -> Arc<Self> {
let (tx_sender, tx_receiver) = mpsc::unbounded_channel();
let socket_ptr = Arc::new(PubSubSocket {
socket,
tx_sender,
tx_receiver,
});
let cloned_ptr = socket_ptr.clone();
tokio::spawn(tx_receiver
.map_err(|e| eprintln!("error in pubsub send queue: {}", e))
.for_each(move |m|
tokio::io::write_all(&cloned_ptr.socket, m.buf)
.map(|_| ())
.map_err(|e| eprintln!("write error: {}", e))));
socket_ptr
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment