5.Network - TCP sockets
The building block of most of the internet is the TCP socket. These socketsprovide a reliable stream of bytes between the connected network devices.This part of the tutorial will show how to use TCP sockets in a few differentcases.
5.1.Star Wars Asciimation
The simplest thing to do is to download data from the internet. In this casewe will use the Star Wars Asciimation service provided by the blinkenlights.nlwebsite. It uses the telnet protocol on port 23 to stream data to anyone thatconnects. It’s very simple to use because it doesn’t require you toauthenticate (give a username or password), you can just start downloading datastraight away.
The first thing to do is make sure we have the socket module available:
>>>importsocket
Then get the IP address of the server:
>>>addr_info=socket.getaddrinfo("towel.blinkenlights.nl",23)
Thegetaddrinfo function actually returns a list of addresses, and eachaddress has more information than we need. We want to get just the first validaddress, and then just the IP address and port of the server. To do this use:
>>>addr=addr_info[0][-1]
If you typeaddr_info andaddr at the prompt you will see exactly whatinformation they hold.
Using the IP address we can make a socket and connect to the server:
>>>s=socket.socket()>>>s.connect(addr)
Now that we are connected we can download and display the data:
>>>whileTrue:...data=s.recv(500)...print(str(data,'utf8'),end='')...
When this loop executes it should start showing the animation (use ctrl-C tointerrupt it).
You should also be able to run this same code on your PC using normal Python ifyou want to try it out there.
5.2.HTTP GET request
The next example shows how to download a webpage. HTTP uses port 80 and youfirst need to send a “GET” request before you can download anything. As partof the request you need to specify the page to retrieve.
Let’s define a function that can download and print a URL:
defhttp_get(url):importsocket_,_,host,path=url.split('/',3)addr=socket.getaddrinfo(host,80)[0][-1]s=socket.socket()s.connect(addr)s.send(bytes('GET /%s HTTP/1.0\r\nHost:%s\r\n\r\n'%(path,host),'utf8'))whileTrue:data=s.recv(100)ifdata:print(str(data,'utf8'),end='')else:breaks.close()
Then you can try:
>>>http_get('http://micropython.org/ks/test.html')
This should retrieve the webpage and print the HTML to the console.
5.3.Simple HTTP server
The following code creates an simple HTTP server which serves a single webpagethat contains a table with the state of all the GPIO pins:
importmachinepins=[machine.Pin(i,machine.Pin.IN)foriin(0,2,4,5,12,13,14,15)]html="""<!DOCTYPE html><html> <head> <title>ESP8266 Pins</title> </head> <body> <h1>ESP8266 Pins</h1> <table border="1"> <tr><th>Pin</th><th>Value</th></tr>%s </table> </body></html>"""importsocketaddr=socket.getaddrinfo('0.0.0.0',80)[0][-1]s=socket.socket()s.bind(addr)s.listen(1)print('listening on',addr)whileTrue:cl,addr=s.accept()print('client connected from',addr)cl_file=cl.makefile('rwb',0)whileTrue:line=cl_file.readline()ifnotlineorline==b'\r\n':breakrows=['<tr><td>%s</td><td>%d</td></tr>'%(str(p),p.value())forpinpins]response=html%'\n'.join(rows)cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')cl.send(response)cl.close()