user2986673
user2986673

Reputation: 171

Very simple Web Service in Python

I am trying to implement a server in Python. When the browser connects to localhost with port number 9999, it will open the file index.html with the images.jpg in that page, but the image can not be shown. How can I make the web server handle the image as well?

Here is my code so far:

from socket import *
import os

serversocket = socket(AF_INET, SOCK_STREAM)
port = 5000
host = '127.0.0.1'

size = os.path.getsize("index.html")
myfile = open('index.html', 'rb')
mycontent = "Welcome to Very Simple Web Server"
size = len(mycontent)
header = "HTTP/1.0 200 OK \r\n Content_Length:" + str(size) + "\r\n\r\n"
mycontent = myfile.read()
serversocket.bind((host, port))
serversocket.listen(5)
print('Server is listening on port 9999')

while (1):
    conn, addr = serversocket.accept()
    print('Connected by', addr)
    conn.send(bytes(header))
    conn.send(mycontent)
    conn.close()

Upvotes: 2

Views: 657

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Your code creates an infinite loop that will just only send one file, and never accepts other connections.

In order for the image to show, the browser has to send another request to the URL of the image, and this request is not being serviced by your code.

In order for your server to work, you need to:

  1. Start a loop
  2. Listen for connections
  3. Interpret the headers of the incoming request, and then act appropriately. Lets assume that you only deal with GET requests and not other things like POST, HEAD, PUT, etc.
  4. Look at the requested resource (the URL)
  5. Find the resource on the file system (so now, you have to parse the URL)
  6. Package the resource into a HTTP response (read the file set the appropriate mime type)
  7. Send the response back to the client with the appropriate headers (the server response headers)
  8. Repeat

To display a HTML page with one image, it takes two requests, one for the HTML page, and another for the image. If the HTML code has a link to a CSS file, now you need three requests - one for the HTML page, one for the CSS file and a final one for the image. All these requests need to be completed successfully in order for the browser to render the page.

You never need to do this by hand, use a web development framework which will take care of all this "boring" stuff so you can then deal with solving the actual problem.

Upvotes: 1

Related Questions