|
META TOPICPARENT |
name="Exercises" |
A WEB Server and the HTTP Protocol
Exercise 1: Write a Hello World WEB Server
Version 1: |
|
< < | Let's start simple and produce a WEB server that simply sends "Hello World!" to the browser when called. In the first version we will create a TCP server creating a stream socket and binding to port 80.
|
> > | Let's start simple and produce a WEB server that just sends "Hello World!" to the browser when called. In the first version we will create 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 incoming an connection request and establishes a connection by accepting it.
|
> > | 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:
|