Last active
March 23, 2019 15:46
-
-
Save pusateri/8d3955ae2d0031047ad0d460f8738d1e to your computer and use it in GitHub Desktop.
Figuring out how to async send message
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
lazy_static! { | |
static ref USMAP: Arc<Mutex<HashMap<String, UpdateServer>>> = Arc::new(Mutex::new(HashMap::new())); | |
} | |
#[derive(Debug)] | |
pub struct UpdateServer { | |
subdomain: String, | |
sa: SocketAddr, | |
sink: SplitSink<UdpFramed<BytesCodec>>, | |
stream: SplitStream<UdpFramed<BytesCodec>>, | |
} | |
impl UpdateServer { | |
pub fn new(_family: Domain, subdomain: String) -> Self { | |
// temporary test server | |
let addr = SocketAddr::new(Ipv4Addr::new(127,0,0,1).into(), 8053); | |
let sock = UdpSocket::bind(&addr).expect("bind failed"); | |
let (a_sink, a_stream) = UdpFramed::new(sock, BytesCodec::new()).split(); | |
UpdateServer { | |
subdomain: subdomain, | |
sa: addr, | |
sink: a_sink, | |
stream: a_stream, | |
} | |
} | |
} | |
pub fn mysend(us: &UpdateServer, msg: Message) | |
{ | |
let task = us.sink.send((msg.as_bytes().clone(), us.sa)) | |
.and_then(|_| { | |
let _a_stream = us.stream.take(1) | |
.into_future() | |
.map(move |(_response, addr)| { | |
println!("task recv from {:?}", addr); | |
}) | |
.map_err(|e| panic!("send update err={:?}", e)); | |
Ok(()) | |
}) | |
.or_else(|n| { | |
println!("read {:?} bytes2", n); | |
Ok(()) | |
}); | |
tokio::spawn(task); | |
} | |
fn main { | |
... | |
let up = UpdateServer::new(Domain::ipv4(), subdomain.clone()); | |
let servers = USMAP.lock().unwrap(); | |
servers.insert(subdomain.clone(), up); | |
... | |
if let Some(ups) = servers.get(&subdomain) { | |
mysend(ups, build_update(&se)); | |
} | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment