diff options
| author | Paul Sokolovsky <pfalcon@users.sourceforge.net> | 2016-08-06 01:56:25 +0300 |
|---|---|---|
| committer | Paul Sokolovsky <pfalcon@users.sourceforge.net> | 2016-08-06 01:59:51 +0300 |
| commit | 3d19adf9b323d6b1f907e6825f19b35670bad0d1 (patch) | |
| tree | 077e8c757d7b58c7b41e00e6eb119e4cd1d4701c /examples/network/http_server.py | |
| parent | d79342d33e4cf7232763a7154fb8bf9273cb4b32 (diff) | |
examples/network: Split recv- and read-based HTTP servers.
Name recv() based a "simplistic", as it can't work robustly in every
environment. All this is to let people concentreate on proper, read()-
based one (and to turn recv() based into a "negative showcase",
explaining what are the pitfalls of such approach).
Diffstat (limited to 'examples/network/http_server.py')
| -rw-r--r-- | examples/network/http_server.py | 47 |
1 files changed, 29 insertions, 18 deletions
diff --git a/examples/network/http_server.py b/examples/network/http_server.py index 147bf5122..e3a66e828 100644 --- a/examples/network/http_server.py +++ b/examples/network/http_server.py @@ -10,7 +10,7 @@ HTTP/1.0 200 OK Hello #%d from MicroPython! """ -def main(use_stream=False): +def main(micropython_optimize=False): s = socket.socket() # Binding to all interfaces - server will be accessible to other hosts! @@ -26,26 +26,37 @@ def main(use_stream=False): counter = 0 while True: res = s.accept() - client_s = res[0] + client_sock = res[0] client_addr = res[1] print("Client address:", client_addr) - print("Client socket:", client_s) - print("Request:") - if use_stream: - # MicroPython socket objects support stream (aka file) interface - # directly. - req = client_s.readline() - print(req) - while True: - h = client_s.readline() - if h == b"" or h == b"\r\n": - break - print(h) - client_s.write(CONTENT % counter) + print("Client socket:", client_sock) + + if not micropython_optimize: + # To read line-oriented protocol (like HTTP) from a socket (and + # avoid short read problem), it must be wrapped in a stream (aka + # file-like) object. That's how you do it in CPython: + client_stream = client_sock.makefile("rwb") else: - print(client_s.recv(4096)) - client_s.send(CONTENT % counter) - client_s.close() + # .. but MicroPython socket objects support stream interface + # directly, so calling .makefile() method is not required. If + # you develop application which will run only on MicroPython, + # especially on a resource-constrained embedded device, you + # may take this shortcut to save resources. + client_stream = client_sock + + print("Request:") + req = client_stream.readline() + print(req) + while True: + h = client_stream.readline() + if h == b"" or h == b"\r\n": + break + print(h) + client_stream.write(CONTENT % counter) + + client_stream.close() + if not micropython_optimize: + client_sock.close() counter += 1 print() |
