Skip to content

Commit c35ea86

Browse files
committed
ch8: add ch8-stdlib example
1 parent fb9e983 commit c35ea86

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

ch8/ch8-stdlib/Cargo.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[package]
2+
name = "ch8-stdlib"
3+
version = "0.1.0"
4+
authors = ["Tim McNamara <[email protected]>"]
5+
edition = "2018"
6+
7+
[dependencies]

ch8/ch8-stdlib/src/main.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
use std::io::prelude::*;
2+
use std::net::TcpStream;
3+
4+
fn main() -> std::io::Result<()> {
5+
let mut connection =
6+
TcpStream::connect("www.rustinaction.com:80")?; // We need to specify the port (80) explicitly,
7+
// TcpStream does not know that this will become a
8+
// HTTP request.
9+
10+
connection.write_all(b"GET / HTTP/1.0")?; // GET is the HTTP method, / is the resource we're
11+
// attempting to access and HTTP/1.0 is the protocol
12+
// version we're requesting. Why 1.0? It does not
13+
// support "keep alive" requests, which will allow
14+
// our stream to close without difficulty.
15+
connection.write_all(b"\r\n")?; // In many networking protocols, \r\n is how a new
16+
// lines
17+
connection
18+
.write_all(b"Host: www.rustinaction.com")?; // The hostname provided on line 5 is actually
19+
// discarded once it is converted to an IP address.
20+
// The Host HTTP header allows the server to know
21+
// which host we're connecting to..
22+
connection.write_all(b"\r\n\r\n")?; // Two blank lines signifies that we've finished the
23+
// request.
24+
25+
std::io::copy(
26+
&mut connection,
27+
&mut std::io::stdout(),
28+
)?; // std::io::copy() streams bytes from a Reader to a
29+
// Writer.
30+
31+
Ok(())
32+
}

0 commit comments

Comments
 (0)