Skip to content

Commit 6c1a0cc

Browse files
committed
Add configuration file with hints for TCP connection handling in Python.
1 parent 476c782 commit 6c1a0cc

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

solutions/python/02-rg2/config.yml

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
hints:
2+
- title_markdown: "How do I access the client's TCP connection?"
3+
body_markdown: |-
4+
This is returned by the [`accept()`](https://docs.python.org/3/library/socket.html#socket.socket.accept) method.
5+
6+
```python
7+
# The return value includes the client's connection (a `Socket` object) and the client's address (which we ignore)
8+
connection, _ = server_socket.accept()
9+
```
10+
11+
The above code uses `_` to ignore the second return value, which is the client's address (a tuple of the IP address and port number).
12+
13+
- title_markdown: "How do I read the client's PING command?"
14+
body_markdown: |-
15+
Use the [`recv()`](https://docs.python.org/3/library/socket.html#socket.socket.recv) method to read the client's command:
16+
17+
```python
18+
# Read 14 bytes from the client's connection
19+
connection.recv(14)
20+
```
21+
22+
The PING command is 14 bytes long when encoded as RESP: `*1\r\n$4\r\nPING\r\n` (you'll learn about RESP in later stages).
23+
24+
- title_markdown: "How do I send the response to the client?"
25+
body_markdown: |-
26+
Use the [`sendall()`](https://docs.python.org/3/library/socket.html#socket.socket.sendall) method on the client's connection for this:
27+
28+
```python
29+
# Send the response to the client
30+
connection.sendall(b"+PONG\r\n")
31+
```
32+
33+
- The above code uses `b` to convert the string to a [bytes object](https://docs.python.org/3/library/stdtypes.html#bytes).
34+
- `+PONG\r\n` is the string "PONG" encoded as a [RESP simple string](https://redis.io/docs/latest/develop/reference/protocol-spec/#simple-strings).

0 commit comments

Comments
 (0)