Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
extern crate actix;
extern crate tokio;
extern crate tokio_codec;
extern crate futures;
extern crate bytes;
use bytes::BytesMut;
use std::io;
use std::net::SocketAddr;
use futures::{Stream, Sink, Future};
use futures::stream::SplitSink;
use tokio::net::{UdpSocket, UdpFramed};
use tokio_codec::BytesCodec;
use actix::prelude::*;
use actix::{Actor, Context, StreamHandler};
struct UdpActor {
sink: SplitSink<UdpFramed<BytesCodec>>
}
impl Actor for UdpActor {
type Context = Context<Self>;
}
#[derive(Message)]
struct UdpPacket(BytesMut, SocketAddr);
impl StreamHandler<UdpPacket, io::Error> for UdpActor {
fn handle(&mut self, msg: UdpPacket, _: &mut Context<Self>) {
println!("Received: ({:?}, {:?})", msg.0, msg.1);
(&mut self.sink).send(("PING\n".into(), msg.1)).wait().unwrap();
}
}
fn main() {
let sys = actix::System::new("echo-udp");
let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let sock = UdpSocket::bind(&addr).unwrap();
println!("{:?}", sock);
let (sink, stream) = UdpFramed::new(sock, BytesCodec::new()).split();
UdpActor::create(|ctx| {
ctx.add_stream(stream.map(|(data, sender)| UdpPacket(data, sender)));
UdpActor{sink: sink}
});
std::process::exit(sys.run());
}
@pingwin

This comment has been minimized.

Copy link

pingwin commented Dec 19, 2018

This code doesn't compile

  --> src/main.rs:31:9
   |
31 |         self.sink.send(("PING".into(), msg.1));
   |         ^^^^^^^^^ cannot move out of borrowed content

error: aborting due to previous error

For more information about this error, try `rustc --explain E0507`.
@apatrushev

This comment has been minimized.

Copy link
Owner Author

apatrushev commented Feb 18, 2019

@pingwin you are free to fix it. At the time of writing it worked of course.

@apatrushev

This comment has been minimized.

Copy link
Owner Author

apatrushev commented Feb 18, 2019

Fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.