1
0
mirror of https://github.com/actix/examples synced 2024-11-23 22:41:07 +01:00

udp echo server example

This commit is contained in:
Anton Patrushev 2019-02-20 22:21:59 +05:00
parent 5c8aaba5f9
commit 2cd0ea9a2e
4 changed files with 77 additions and 0 deletions

View File

@ -30,6 +30,7 @@ members = [
"tls", "tls",
"rustls", "rustls",
"unix-socket", "unix-socket",
"udp-echo",
"web-cors/backend", "web-cors/backend",
"websocket", "websocket",
"websocket-chat", "websocket-chat",

11
udp-echo/Cargo.toml Normal file
View File

@ -0,0 +1,11 @@
[package]
name = "udp-echo"
version = "0.1.0"
authors = ["Anton Patrushev <apatrushev@gmail.com>"]
edition = "2018"
[dependencies]
actix = "0.7"
tokio = "*"
futures = "*"
bytes = "*"

18
udp-echo/README.md Normal file
View File

@ -0,0 +1,18 @@
# udp-echo
## Usage
### server
```bash
cd examples/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
```

47
udp-echo/src/main.rs Normal file
View File

@ -0,0 +1,47 @@
extern crate actix;
extern crate bytes;
extern crate futures;
extern crate tokio;
use actix::{Actor, AsyncContext, Context, Message, StreamHandler};
use bytes::BytesMut;
use futures::stream::SplitSink;
use futures::{Future, Sink, Stream};
use std::net::SocketAddr;
use tokio::codec::BytesCodec;
use tokio::net::{UdpFramed, UdpSocket};
struct UdpActor {
sink: SplitSink<UdpFramed<BytesCodec>>,
}
impl Actor for UdpActor {
type Context = Context<Self>;
}
#[derive(Message)]
struct UdpPacket(BytesMut, SocketAddr);
impl StreamHandler<UdpPacket, std::io::Error> for UdpActor {
fn handle(&mut self, msg: UdpPacket, _: &mut Context<Self>) {
println!("Received: ({:?}, {:?})", msg.0, msg.1);
(&mut self.sink).send((msg.0.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!(
"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.map(|(data, sender)| UdpPacket(data, sender)));
UdpActor { sink: sink }
});
std::process::exit(sys.run());
}