Line: 1 to 1 | ||||||||
---|---|---|---|---|---|---|---|---|
A WEB Server on the ESP32A "Hello World!" WEB server | ||||||||
Line: 12 to 12 | ||||||||
Version 1 | ||||||||
Changed: | ||||||||
< < | Let's start simple and produce a WEB server that just sends "Hello World!" to the browser when called. You may add some HTML text if desired. In the first version we will write a TCP server creating a stream socket and binding to port 80. s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: s.bind(('',80)) except OSError as exception: if exception.args[0] == uerrno.EADDRINUSE: print("Socket is already bound, please reset the machine") sys.exit() The server then starts listening for an incoming connection request and establishes a connection by accepting it. s.listen(5) print("Starting the Hello World WEB server on IP address ",ipaddr,"port 80") while True: conn,addr=s.accept() print("GOT a connection from %s" % str(addr)) Finally it reads an http request from the connection and answers with its Hello World page: request=conn.recv(1024) print("Content %s" % str(request)) request=str(request) response=html conn.send(response) conn.close() html is the http string to be sent, e.g. html = """ <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <title>Hello World </title> <h1>The Hello World! HTML page</h1> <p>Hello World!</p> </body> </html> """ Please check https://docs.micropython.org/en/latest/library/usocket.html for more details. | |||||||
> > | Version 1 is the basic WEB server we implemented in BasicWEBServer | |||||||
Version 2:In the second version we will separate the HTML text from the server and store it in the html directory (to be created with ampy: ampy mkdir /html) on the ESP32. Now we can use a ready made Web server for MicroPython, picoweb to serve the page. picoweb and utemplates (see exercise 2) are already included in the MicroPython binary. |