http_server_ssl.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. try:
  2. import usocket as socket
  3. except:
  4. import socket
  5. import ussl as ssl
  6. CONTENT = b"""\
  7. HTTP/1.0 200 OK
  8. Hello #%d from MicroPython!
  9. """
  10. def main(use_stream=True):
  11. s = socket.socket()
  12. # Binding to all interfaces - server will be accessible to other hosts!
  13. ai = socket.getaddrinfo("0.0.0.0", 8443)
  14. print("Bind address info:", ai)
  15. addr = ai[0][-1]
  16. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  17. s.bind(addr)
  18. s.listen(5)
  19. print("Listening, connect your browser to https://<this_host>:8443/")
  20. counter = 0
  21. while True:
  22. res = s.accept()
  23. client_s = res[0]
  24. client_addr = res[1]
  25. print("Client address:", client_addr)
  26. print("Client socket:", client_s)
  27. client_s = ssl.wrap_socket(client_s, server_side=True)
  28. print(client_s)
  29. print("Request:")
  30. if use_stream:
  31. # Both CPython and MicroPython SSLSocket objects support read() and
  32. # write() methods.
  33. # Browsers are prone to terminate SSL connection abruptly if they
  34. # see unknown certificate, etc. We must continue in such case -
  35. # next request they issue will likely be more well-behaving and
  36. # will succeed.
  37. try:
  38. req = client_s.readline()
  39. print(req)
  40. while True:
  41. h = client_s.readline()
  42. if h == b"" or h == b"\r\n":
  43. break
  44. print(h)
  45. if req:
  46. client_s.write(CONTENT % counter)
  47. except Exception as e:
  48. print("Exception serving request:", e)
  49. else:
  50. print(client_s.recv(4096))
  51. client_s.send(CONTENT % counter)
  52. client_s.close()
  53. counter += 1
  54. print()
  55. main()