Last active
June 7, 2023 23:44
-
-
Save apatrushev/4bbddb65e9a35a72047e3b9993c6636e to your computer and use it in GitHub Desktop.
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
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()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed