create new tag
view all tags

Writing a WEB server from scratch

We do not want to re-invent the wheel, and we will use a WEB server framework already prepared for us by professional programmers. It is nevertheless interesting to implement a very primitive WEB server ourselves, simply to understand the basic principles.

The Hello World WEB Server

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.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
except OSError as exception:      
    if exception.args[0] = uerrno.EADDRINUSE:
          print("Socket is already bound, please reset the machine") 

The server then starts listening for an incoming connection request and establishes a connection by accepting it.

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:

print("Content %s" % str(request))

HTML is the HTTP string to be sent, e.g.

html = """ <!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Hello World </title>
<h1>The Hello World! HTML page</h1>
<p>Hello World!</p>


Please check https://docs.micropython.org/en/latest/library/usocket.html for more details.

Here is the complete program:


-- Uli Raich - 2020-06-08


Edit | Attach | Watch | Print version | History: r3 < r2 < r1 | Backlinks | Raw View | Raw edit | More topic actions
Topic revision: r3 - 2022-11-12 - UliRaich
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2024 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback