File: udp-client.rs

package info (click to toggle)
rust-async-std 1.13.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,992 kB
  • sloc: sh: 13; makefile: 8
file content (34 lines) | stat: -rw-r--r-- 767 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//! UDP client.
//!
//! First start the echo server:
//!
//! ```sh
//! $ cargo run --example udp-echo
//! ```
//!
//! Then run the client:
//!
//! ```sh
//! $ cargo run --example udp-client
//! ```

use async_std::io;
use async_std::net::UdpSocket;
use async_std::task;

fn main() -> io::Result<()> {
    task::block_on(async {
        let socket = UdpSocket::bind("127.0.0.1:8081").await?;
        println!("Listening on {}", socket.local_addr()?);

        let msg = "hello world";
        println!("<- {}", msg);
        socket.send_to(msg.as_bytes(), "127.0.0.1:8080").await?;

        let mut buf = vec![0u8; 1024];
        let (n, _) = socket.recv_from(&mut buf).await?;
        println!("-> {}\n", String::from_utf8_lossy(&buf[..n]));

        Ok(())
    })
}