1
0
mirror of https://github.com/actix/examples synced 2025-06-28 18:00:37 +02:00

delete udp echo example

This commit is contained in:
Rob Ede
2022-01-29 16:06:32 +00:00
parent a3a4786d00
commit 062a3af80c
5 changed files with 83 additions and 153 deletions

View File

@ -1,14 +0,0 @@
[package]
name = "udp-echo"
version = "0.1.0"
authors = ["Anton Patrushev <apatrushev@gmail.com>"]
edition = "2018"
[dependencies]
actix = "0.10"
actix-rt = "1.1"
tokio = "0.2"
tokio-util = { version = "0.3", features = [ "codec", "udp" ] }
futures = "0.3"
futures-util = "0.3"
bytes = "0.5"

View File

@ -1,18 +0,0 @@
# udp-echo
## Usage
### server
```bash
cd other/udp-echo
cargo run
# Started http server: 127.0.0.1:12345
```
### socat client
Copy port provided in server output and run following command to communicate
with the udp server:
```bash
socat - UDP4:localhost:12345
```

View File

@ -1,57 +0,0 @@
use actix::io::SinkWrite;
use actix::{Actor, AsyncContext, Context, Message, StreamHandler};
use bytes::Bytes;
use bytes::BytesMut;
use futures::stream::SplitSink;
use futures_util::stream::StreamExt;
use std::io::Result;
use std::net::SocketAddr;
use tokio::net::UdpSocket;
use tokio_util::codec::BytesCodec;
use tokio_util::udp::UdpFramed;
type SinkItem = (Bytes, SocketAddr);
type UdpSink = SplitSink<UdpFramed<BytesCodec>, SinkItem>;
struct UdpActor {
sink: SinkWrite<SinkItem, UdpSink>,
}
impl Actor for UdpActor {
type Context = Context<Self>;
}
#[derive(Message)]
#[rtype(result = "()")]
struct UdpPacket(BytesMut, SocketAddr);
impl StreamHandler<UdpPacket> for UdpActor {
fn handle(&mut self, msg: UdpPacket, _: &mut Context<Self>) {
println!("Received: ({:?}, {:?})", msg.0, msg.1);
self.sink.write((msg.0.into(), msg.1)).unwrap();
}
}
impl actix::io::WriteHandler<std::io::Error> for UdpActor {}
#[actix_rt::main]
async fn main() {
let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let sock = UdpSocket::bind(&addr).await.unwrap();
println!(
"Started udp server on: 127.0.0.1:{:?}",
sock.local_addr().unwrap().port()
);
let (sink, stream) = UdpFramed::new(sock, BytesCodec::new()).split();
UdpActor::create(|ctx| {
ctx.add_stream(stream.filter_map(
|item: Result<(BytesMut, SocketAddr)>| async {
item.map(|(data, sender)| UdpPacket(data, sender)).ok()
},
));
UdpActor {
sink: SinkWrite::new(sink, ctx),
}
});
actix_rt::Arbiter::local_join().await;
}