http_server.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. try:
  2. import usocket as socket
  3. except:
  4. import socket
  5. CONTENT = b"""\
  6. HTTP/1.0 200 OK
  7. Hello #%d from MicroPython!
  8. """
  9. def main(micropython_optimize=False):
  10. s = socket.socket()
  11. # Binding to all interfaces - server will be accessible to other hosts!
  12. ai = socket.getaddrinfo("0.0.0.0", 8080)
  13. print("Bind address info:", ai)
  14. addr = ai[0][-1]
  15. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  16. s.bind(addr)
  17. s.listen(5)
  18. print("Listening, connect your browser to http://<this_host>:8080/")
  19. counter = 0
  20. while True:
  21. res = s.accept()
  22. client_sock = res[0]
  23. client_addr = res[1]
  24. print("Client address:", client_addr)
  25. print("Client socket:", client_sock)
  26. if not micropython_optimize:
  27. # To read line-oriented protocol (like HTTP) from a socket (and
  28. # avoid short read problem), it must be wrapped in a stream (aka
  29. # file-like) object. That's how you do it in CPython:
  30. client_stream = client_sock.makefile("rwb")
  31. else:
  32. # .. but MicroPython socket objects support stream interface
  33. # directly, so calling .makefile() method is not required. If
  34. # you develop application which will run only on MicroPython,
  35. # especially on a resource-constrained embedded device, you
  36. # may take this shortcut to save resources.
  37. client_stream = client_sock
  38. print("Request:")
  39. req = client_stream.readline()
  40. print(req)
  41. while True:
  42. h = client_stream.readline()
  43. if h == b"" or h == b"\r\n":
  44. break
  45. print(h)
  46. client_stream.write(CONTENT % counter)
  47. client_stream.close()
  48. if not micropython_optimize:
  49. client_sock.close()
  50. counter += 1
  51. print()
  52. main()