Trying to convert some old code from python 2.x to 3.9. Building a simple web server, works as far as going to localhost:8000 and showing the 404 intended. But when I actually try to access localhost:8000/file.html with it then I get an error.
Error:
line 17, in <module>
connectionSocket.send(outputdata[i])
TypeError: a bytes-like object is required, not 'str'
Whole code:
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 8000
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
while True:
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1500)
filepath = message.split()[1]
f = open(filepath[1:])
outputdata = f.read()
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.send("\r\n")
connectionSocket.close()
except IOError:
bytes('', 'UTF-8')
connectionSocket.send(bytes("HTTP/1.1 404 Not Found\r\n\r\n", "UTF-8"))
connectionSocket.send(bytes("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n", "UTF-8"))
connectionSocket.close()
serverSocket.close()
Would really appreciate some help.