PageRenderTime 106ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/unix/sock-server.py

https://github.com/jtbattle/micropython
Python | 41 lines | 39 code | 2 blank | 0 comment | 1 complexity | 938c9213f281326b9af92e6df5282a99 MD5 | raw file
  1. try:
  2. import microsocket as socket
  3. except:
  4. import socket
  5. CONTENT = """\
  6. HTTP/1.0 200 OK
  7. Hello #{} from MicroPython!
  8. """
  9. s = socket.socket()
  10. ai = socket.getaddrinfo("127.0.0.1", 8080)
  11. print("Bind address info:", ai)
  12. addr = ai[0][4]
  13. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  14. s.bind(addr)
  15. s.listen(5)
  16. print("Listening, connect your browser to http://127.0.0.1:8080/")
  17. counter = 0
  18. while True:
  19. res = s.accept()
  20. client_s = res[0]
  21. client_addr = res[1]
  22. print("Client address:", client_addr)
  23. print("Client socket:", client_s)
  24. print("Request:")
  25. if 0:
  26. # MicroPython rawsocket module supports file interface directly
  27. print(client_s.read(4096))
  28. #print(client_s.readall())
  29. client_s.write(CONTENT.format(counter))
  30. else:
  31. print(client_s.recv(4096))
  32. client_s.send(bytes(CONTENT.format(counter), "ascii"))
  33. client_s.close()
  34. counter += 1