Skip to content

Instantly share code, notes, and snippets.

@apatrushev
Last active June 7, 2023 23:44
Show Gist options
  • Save apatrushev/4bbddb65e9a35a72047e3b9993c6636e to your computer and use it in GitHub Desktop.
Save apatrushev/4bbddb65e9a35a72047e3b9993c6636e to your computer and use it in GitHub Desktop.
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
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
Copy link
Author

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

@apatrushev
Copy link
Author

Fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment