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