8000 Sockets and threads. · pythonpeixun/practice-python@d399ad7 · GitHub
[go: up one dir, main page]

Skip to content

Commit d399ad7

Browse files
committed
Sockets and threads.
1 parent a0e887e commit d399ad7

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

experiments/sockets/fib.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
"""
2+
Really bad Fibonacci implementation
3+
"""
4+
5+
6+
def fib(n):
7+
if n <= 2:
8+
return 1
9+
10+
return fib(n - 1) + fib(n - 2)

experiments/sockets/server.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
Microservice for Fibonacci
3+
"""
4+
5+
from socket import *
6+
from fib import fib
7+
8+
9+
def fib_server(address):
10+
sock = socket(AF_INET, SOCK_STREAM)
11+
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
12+
sock.bind(address)
13+
sock.listen(5)
14+
15+
while True:
16+
client, addr = sock.accept()
17+
print("Connected on {}", addr)
18+
fib_handler(client)
19+
20+
21+
def fib_handler(client):
22+
while True:
23+
req = client.recv(100)
24+
if not req:
25+
break
26+
n = int(req)
27+
result = fib(n)
28+
resp = str(result).encode('ascii') + b'\n'
29+
client.send(resp)
30+
31+
print("Closed")
32+
33+
34+
fib_server(('', 25000))

0 commit comments

Comments
 (0)
0