Micropython: Network TCP Sockets - lvidarte/esp8266 GitHub Wiki

The building block of most of the internet is the TCP socket. These sockets provide a reliable stream of bytes between the connected network devices.

Star Wars Asciimation

The simplest thing to do is to download data from the internet. In this case we will use the Star Wars Asciimation service provided by the blinkenlights.nl website. It uses the telnet protocol on port 23 to stream data to anyone that connects. It’s very simple to use because it doesn’t require you to authenticate (give a username or password), you can just start downloading data straight away.

>>> import socket
>>> addr_info = socket.getaddrinfo("towel.blinkenlights.nl", 23)
>>> addr = addr_info[0][-1]
>>> s = socket.socket()
>>> s.connect(addr)

Now that we are connected we can download and display the data:

>>> while True:
...     data = s.recv(500)
...     print(str(data, 'utf8'), end='')
...

More abstraction

MicroPython comes with the module urequests which is a very small port from the requests library.

>>> import urequests 
>>> r = urequests.get("https://en.wikipedia.org/w/api.php?action=opensearch&search=micropython&limit=1&format=json").json()
>>> r
['micropython', ['MicroPython'], ['MicroPython  is an software implementation of the Python 3 programming language, written in C, that is optimized to run on a microcontroller.'], ['https://en.wikipedia.org/wiki/MicroPython']]
>>> r[-1][0]
'https://en.wikipedia.org/wiki/MicroPython'