Search code examples
pythonpython-3.xwebserver

List Index Out of Range error in python web server


I am using localhost with port number 6789 to test my web server. It works when I send the first request whether it's to find a file that exists or a file that does not exist. When I try to send a second request right after, I get IndexError:list index out of range at:

f = open(filename[1:])

My connection is persistent but I am not sure if I'm supposed to send one request at a time.

My code

import socket
import sys # In order to terminate the program

serverPort = 6789
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Prepare a sever socket
serverSocket.bind(('',serverPort))
serverSocket.listen(1)

while True:
   #Establish the connection
   print('Ready to serve...')
   connectionSocket, addr = serverSocket.accept()
   try:
      message = connectionSocket.recv(1024)
      filename = message.split()[1]
      f = open(filename[1:])
      outputdata = f.read() 
      #Send one HTTP header line into socket
      connectionSocket.send(bytes('HTTP/1.1 200 OK\r\n\r\n',"UTF-8"))
      #Send the content of the requested file to the client
      for i in range(0, len(outputdata)):
         connectionSocket.send(outputdata[i].encode())
      connectionSocket.send("\r\n".encode())
      connectionSocket.close()
   except IOError:
      print("404 not found")
      connectionSocket.send(bytes('HTTP/1.1 404 NOT FOUND\r\n\r\n',"UTF-8"))
      connectionSocket.close()
      
      
serverSocket.close()
sys.exit()

Solution

  • I was able to figure this out. I needed to check if message was empty or not.

     message = connectionSocket.recv(1024)
     m = message.split()
     if m:
              print(m[1])
              filename = message.split()[1]
              f = open(filename[1:])
              outputdata = f.read() 
              f.close()
              connectionSocket.send(bytes('HTTP/1.1 200 OK\r\n\r\n','UTF-8'))
              for i in range(0, len(outputdata)):
                  connectionSocket.send(outputdata[i].encode())
              connectionSocket.send("\r\n".encode())
              connectionSocket.close()
          else: 
              #handling None values
              print("file not found")
              connectionSocket.close()