|
1 | 1 | hints: |
2 | 2 | - title_markdown: "How do I access the client's TCP connection?" |
3 | 3 | body_markdown: |- |
4 | | - This is returned by the [`incoming()`](https://doc.rust-lang.org/std/net/struct.TcpListener.html#method.incoming) method. |
| 4 | + Use the [`incoming()`](https://doc.rust-lang.org/std/net/struct.TcpListener.html#method.incoming) method on the listener to get the client connection: |
5 | 5 |
|
6 | 6 | ```rust |
7 | 7 | // The return value is an iterator that provides a sequence of `TcpStream` objects. |
8 | | - for stream in listener.incoming() |
| 8 | + for stream in listener.incoming() { |
| 9 | + match stream { |
| 10 | + Ok(mut stream) => { |
| 11 | + // Handle the connection here |
| 12 | + } |
| 13 | + Err(e) => { |
| 14 | + println!("Error: {}", e); |
| 15 | + } |
| 16 | + } |
| 17 | + } |
9 | 18 | ``` |
10 | 19 |
|
11 | 20 | Each [`TcpStream`](https://doc.rust-lang.org/std/net/struct.TcpStream.html) represents an active connection from a client. |
12 | 21 |
|
13 | | - - title_markdown: "How do I send a response to the client?" |
| 22 | + - title_markdown: 'How do I send a response to the client?' |
14 | 23 | body_markdown: |- |
15 | 24 | Use the [`write_all()`](https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all) method on the client's connection: |
16 | 25 |
|
17 | 26 | ```rust |
| 27 | + use std::io::Write; |
| 28 | +
|
| 29 | + // Inside your match Ok(mut stream) => { ... } block |
18 | 30 | // Send the response to the client |
19 | 31 | stream.write_all(b"+PONG\r\n").unwrap(); |
20 | 32 | ``` |
21 | 33 |
|
22 | | - - The above code uses `b` to create a [byte string literal](https://doc.rust-lang.org/reference/tokens.html#byte-string-literals). |
| 34 | + - To use `write_all()`, you need to import the [Write](https://doc.rust-lang.org/std/io/trait.Write.html) trait and mark the `TcpStream` as [mutable](https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html). |
| 35 | + - The `b` prefix converts the string to a [byte string literal](https://doc.rust-lang.org/reference/tokens.html#byte-string-literals). |
23 | 36 | - `+PONG\r\n` is the string "PONG" encoded as a [RESP simple string](https://redis.io/docs/latest/develop/reference/protocol-spec/#simple-strings). |
24 | | - - To satisfy the Rust compiler, you also need to import the [Write](https://doc.rust-lang.org/std/io/trait.Write.html) trait and mark the TcpStream as [mutable](https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html) in order to use `write_all()`. |
|
0 commit comments