async-std/examples/tcp-client.rs

36 lines
775 B
Rust
Raw Normal View History

2019-08-08 12:44:48 +00:00
//! TCP client.
//!
//! First start the echo server:
//!
//! ```sh
//! $ cargo run --example tcp-echo
//! ```
//!
//! Then run the client:
//!
//! ```sh
//! $ cargo run --example tcp-client
//! ```
2019-08-14 01:47:39 +00:00
use async_std::io;
use async_std::net::TcpStream;
2019-08-14 02:22:37 +00:00
use async_std::prelude::*;
2019-08-14 01:47:39 +00:00
use async_std::task;
2019-08-08 12:44:48 +00:00
fn main() -> io::Result<()> {
task::block_on(async {
2019-08-12 10:44:57 +00:00
let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
2019-08-08 12:44:48 +00:00
println!("Connected to {}", &stream.peer_addr()?);
let msg = "hello world";
println!("<- {}", msg);
stream.write_all(msg.as_bytes()).await?;
let mut buf = vec![0u8; 1024];
let n = stream.read(&mut buf).await?;
println!("-> {}\n", String::from_utf8_lossy(&buf[..n]));
Ok(())
})
}