Search code examples
pythonservernetwork-programming

TypeError: bytes-like object is required, not 'str'


The purpose of the code below is, to check if the server is running and the HTML file code is accessible, if not then send the error " 404 Not Found ". For example: if the user writes

localhost:6789/hello.html

the output will be = hello but if he writes

localhost:6789/hello1.html

then the output will be " 404 not found " in the browser.

but the code below works for the first output but for the second output, it gives me the following error.

 connectionSocket.send("\nHTTP/1.1 200 OK\n")
TypeError: a bytes-like object is required, not 'str'

The Complete implemented code is given below.

# import socket module
from socket import *
import sys
#import socket
# In order to terminate the program

# Create a TCP server socket
# (AF_INET is used for IPv4 protocols)
# (SOCK_STREAM is used for TCP)
serverPort = 6789
serverSocket = socket(AF_INET, SOCK_STREAM)

'''***Prepare a server socket***'''

# Fill in start

serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print(f"The web server is up on the port {serverSocket}")
# Fill in end

while True:
    # Establish the connection
    print("Ready to serve...")
    # Fill in start
    connectionSocket, addr = serverSocket.accept()
    # Fill in end

    try:
        # Fill in start
        message = connectionSocket.recv(1024)
        print(message, "\n" '::', message.split()[0], "\n" ':', message.split()[1])
        filename = message.split()[1]
        print(filename, "||", filename[1:])
        # Fill in end
        f = open(filename[1:])
        outputData = f.read()
        # print(outputData)
        # Send one HTTP header line into socket
        # Fill in start
        connectionSocket.send("\nHTTP/1.1 200 OK\n")
       # connectionSocket.send(outputData)
        # Fill in end

        # 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:
        # Send response message for file not found
        # Fill in start
        connectionSocket.send("\nHTTP/1.1 404 Not Found \n\r\n")
        # Fill in end
        # Close client socket
        # Fill in start
        connectionSocket.send("<html> <head> </head><body><h1> 404 Not Found </h1> </body></html>\r\n")
        connectionSocket.close()
    # Fill in end

serverSocket.close()
sys.exit()  # Terminate the program after sending the corresponding data

Solution

  • convert your string to bytes with b like below

    connectionSocket.send(b"\nHTTP/1.1 200 OK\n")