2014-01-20 18:35:18 +00:00
|
|
|
try:
|
2014-10-09 18:43:10 +01:00
|
|
|
import usocket as socket
|
2014-01-20 18:35:18 +00:00
|
|
|
except:
|
|
|
|
import socket
|
2014-01-18 21:49:06 +00:00
|
|
|
|
2014-01-20 18:35:18 +00:00
|
|
|
|
2016-04-02 18:53:29 +01:00
|
|
|
CONTENT = b"""\
|
2014-01-20 18:35:18 +00:00
|
|
|
HTTP/1.0 200 OK
|
|
|
|
|
2016-04-02 18:53:29 +01:00
|
|
|
Hello #%d from MicroPython!
|
2014-01-20 18:35:18 +00:00
|
|
|
"""
|
|
|
|
|
2016-04-02 18:57:58 +01:00
|
|
|
def main(use_stream=False):
|
|
|
|
s = socket.socket()
|
|
|
|
|
2016-04-02 21:14:19 +01:00
|
|
|
# Binding to all interfaces - server will be accessible to other hosts!
|
|
|
|
ai = socket.getaddrinfo("0.0.0.0", 8080)
|
2016-04-02 18:57:58 +01:00
|
|
|
print("Bind address info:", ai)
|
|
|
|
addr = ai[0][4]
|
|
|
|
|
|
|
|
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
|
|
s.bind(addr)
|
|
|
|
s.listen(5)
|
2016-04-02 21:14:19 +01:00
|
|
|
print("Listening, connect your browser to http://<this_host>:8080/")
|
2016-04-02 18:57:58 +01: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()
|