mirror of
https://github.com/actix/examples
synced 2024-11-23 22:41:07 +01:00
Merge pull request #79 from apatrushev/udp-echo
Add udp echo server example
This commit is contained in:
commit
fb6d5254bf
@ -32,6 +32,7 @@ members = [
|
||||
"template_yarte",
|
||||
"template_handlebars",
|
||||
"tls",
|
||||
"udp-echo",
|
||||
"unix-socket",
|
||||
"web-cors/backend",
|
||||
"websocket",
|
||||
|
11
udp-echo/Cargo.toml
Normal file
11
udp-echo/Cargo.toml
Normal 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 = "0.1"
|
||||
futures = "0.1"
|
||||
bytes = "0.4"
|
18
udp-echo/README.md
Normal file
18
udp-echo/README.md
Normal 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
|
||||
```
|
42
udp-echo/src/main.rs
Normal file
42
udp-echo/src/main.rs
Normal file
@ -0,0 +1,42 @@
|
||||
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());
|
||||
}
|
Loading…
Reference in New Issue
Block a user