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
|
|
|
"""
|
|
|
|
|
2016-04-02 13:57:58 -04:00
|
|
|
def main(use_stream=False):
|
|
|
|
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()
|
|
|
|
client_s = 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.
|
|
|
|
print(client_s.read(4096))
|
|
|
|
client_s.write(CONTENT % counter)
|
|
|
|
else:
|
|
|
|
print(client_s.recv(4096))
|
|
|
|
client_s.send(CONTENT % counter)
|
|
|
|
client_s.close()
|
|
|
|
counter += 1
|
|
|
|
print()
|
|
|
|
|
|
|
|
|
|
|
|
main()
|