Skip to content

Commit c07a03a

Browse files
committed
examples/http_server.py: Introduce main() function.
Allows to re-run code if it was imported as a module (e.g., on bare-metal ports).
1 parent aa3fb7b commit c07a03a

1 file changed

Lines changed: 34 additions & 30 deletions

File tree

examples/network/http_server.py

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -10,33 +10,37 @@
1010
Hello #%d from MicroPython!
1111
"""
1212

13-
s = socket.socket()
14-
15-
ai = socket.getaddrinfo("127.0.0.1", 8080)
16-
print("Bind address info:", ai)
17-
addr = ai[0][4]
18-
19-
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
20-
s.bind(addr)
21-
s.listen(5)
22-
print("Listening, connect your browser to http://127.0.0.1:8080/")
23-
24-
counter = 0
25-
while True:
26-
res = s.accept()
27-
client_s = res[0]
28-
client_addr = res[1]
29-
print("Client address:", client_addr)
30-
print("Client socket:", client_s)
31-
print("Request:")
32-
if 0:
33-
# MicroPython socket objects support stream (aka file) interface
34-
# directly.
35-
print(client_s.read(4096))
36-
client_s.write(CONTENT % counter)
37-
else:
38-
print(client_s.recv(4096))
39-
client_s.send(CONTENT % counter)
40-
client_s.close()
41-
counter += 1
42-
print()
13+
def main(use_stream=False):
14+
s = socket.socket()
15+
16+
ai = socket.getaddrinfo("127.0.0.1", 8080)
17+
print("Bind address info:", ai)
18+
addr = ai[0][4]
19+
20+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
21+
s.bind(addr)
22+
s.listen(5)
23+
print("Listening, connect your browser to http://127.0.0.1:8080/")
24+
25+
counter = 0
26+
while True:
27+
res = s.accept()
28+
client_s = res[0]
29+
client_addr = res[1]
30+
print("Client address:", client_addr)
31+
print("Client socket:", client_s)
32+
print("Request:")
33+
if use_stream:
34+
# MicroPython socket objects support stream (aka file) interface
35+
# directly.
36+
print(client_s.read(4096))
37+
client_s.write(CONTENT % counter)
38+
else:
39+
print(client_s.recv(4096))
40+
client_s.send(CONTENT % counter)
41+
client_s.close()
42+
counter += 1
43+
print()
44+
45+
46+
main()

0 commit comments

Comments
 (0)