TASK
Implementation
Build a TCP echo server using raw syscalls. No standard library network abstractions allowed. The server should:
- Create a socket using
socket(AF_INET, SOCK_STREAM, 0) - Bind to a port using
bind() - Listen for connections using
listen() - Accept connections using
accept() - Read data using
read() - Write data back using
write()
Implement a Maelstrom node that simulates this:
Request: {"type": "tcp_echo_start", "msg_id": 1, "port": 8080}
Response: {"type": "tcp_echo_start_ok", "in_reply_to": 1, "status": "listening", "port": 8080}
Request: {"type": "tcp_echo_send", "msg_id": 2, "data": "hello world"}
Response: {"type": "tcp_echo_send_ok", "in_reply_to": 2, "echoed": "hello world", "bytes": 11}
Request: {"type": "tcp_echo_stats", "msg_id": 3}
Response: {"type": "tcp_echo_stats_ok", "in_reply_to": 3, "total_connections": 1, "total_bytes": 11}Sample Test Cases
Start echo serverTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"tcp_echo_start","msg_id":2,"port":8080}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "tcp_echo_start_ok", "in_reply_to": 2, "status": "listening", "port": 8080, "msg_id": 1}}
Echo data back correctlyTimeout: 5000ms
Input
{"src":"c0","dest":"n1","body":{"type":"init","msg_id":1,"node_id":"n1","node_ids":["n1"]}}
{"src":"c1","dest":"n1","body":{"type":"tcp_echo_start","msg_id":2,"port":8080}}
{"src":"c1","dest":"n1","body":{"type":"tcp_echo_send","msg_id":3,"data":"hello world"}}
Expected Output
{"src": "n1", "dest": "c0", "body": {"type": "init_ok", "in_reply_to": 1, "msg_id": 0}}
{"src": "n1", "dest": "c1", "body": {"type": "tcp_echo_start_ok", "in_reply_to": 2, "status": "listening", "port": 8080, "msg_id": 1}}
{"src": "n1", "dest": "c1", "body": {"type": "tcp_echo_send_ok", "in_reply_to": 3, "echoed": "hello world", "bytes": 11, "msg_id": 2}}
Hints
Hint 1▾
Use raw socket syscalls: socket(), bind(), listen(), accept(), read(), write()
Hint 2▾
Do not use high-level network abstractions from the standard library
Hint 3▾
The echo server reads data from a client and writes it back unchanged
Hint 4▾
Use SOCK_STREAM for TCP and AF_INET for IPv4
Hint 5▾
Close client connections properly after echoing
OVERVIEW
Theoretical Hub
Concept overview coming soon
Key Concepts
TCPsocketbindlistenacceptsyscalls
main.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python3
import sys
import json
def main():
# Your implementation here
for line in sys.stdin:
msg = json.loads(line)
print(json.dumps(msg), flush=True)
if __name__ == "__main__":
main()