2014-01-20 13:35:18 -05:00
|
|
|
try:
|
2014-10-09 13:43:10 -04:00
|
|
|
import usocket as socket
|
2014-01-20 13:35:18 -05:00
|
|
|
except:
|
|
|
|
import socket
|
2014-01-18 16:49:06 -05:00
|
|
|
|
2014-01-20 13:35:18 -05:00
|
|
|
|
2016-04-02 13:53:29 -04:00
|
|
|
CONTENT = b"""\
|
2014-01-20 13:35:18 -05:00
|
|
|
HTTP/1.0 200 OK
|
|
|
|
|
2016-04-02 13:53:29 -04:00
|
|
|
Hello #%d from MicroPython!
|
2014-01-20 13:35:18 -05:00
|
|
|
"""
|
|
|
|
|
2020-02-26 23:36:53 -05:00
|
|
|
|
2016-08-05 18:56:25 -04:00
|
|
|
def main(micropython_optimize=False):
|
2016-04-02 13:57:58 -04:00
|
|
|
s = socket.socket()
|
|
|
|
|
2016-04-02 16:14:19 -04:00
|
|
|
# Binding to all interfaces - server will be accessible to other hosts!
|
|
|
|
ai = socket.getaddrinfo("0.0.0.0", 8080)
|
2016-04-02 13:57:58 -04:00
|
|
|
print("Bind address info:", ai)
|
2016-05-02 17:45:37 -04:00
|
|
|
addr = ai[0][-1]
|
2016-04-02 13:57:58 -04:00
|
|
|
|
|
|
|
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
|
|
s.bind(addr)
|
|
|
|
s.listen(5)
|
2016-04-02 16:14:19 -04:00
|
|
|
print("Listening, connect your browser to http://<this_host>:8080/")
|
2016-04-02 13:57:58 -04:00
|
|
|
|
|
|
|
counter = 0
|
|
|
|
while True:
|
|
|
|
res = s.accept()
|
2016-08-05 18:56:25 -04:00
|
|
|
client_sock = res[0]
|
2016-04-02 13:57:58 -04:00
|
|
|
client_addr = res[1]
|
|
|
|
print("Client address:", client_addr)
|
2016-08-05 18:56:25 -04:00
|
|
|
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")
|
2016-04-02 13:57:58 -04:00
|
|
|
else:
|
2016-08-05 18:56:25 -04:00
|
|
|
# .. 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()
|
2016-04-02 13:57:58 -04:00
|
|
|
counter += 1
|
|
|
|
print()
|
|
|
|
|
|
|
|
|
|
|
|
main()
|