Question: Hello! I am working on socket programming with python. I keep recieving a a bytes-like object is required, not 'str' error. I believe the issue

Hello! I am working on socket programming with python. I keep recieving a "a bytes-like object is required, not 'str'" error. I believe the issue has to do with how I encoded the message but I am not sure. How can I avoid this error in the future?

# Import socket module from socket import *  # TODO-Create a TCP server socket (using IPv4 address) serverSocket = socket(AF_INET, SOCK_STREAM) #TODO-Assign a port number (outside 0 to 1023) serverPort = 6789 # TODO-Bind the socket to server address(loopback or localhost address) and server port serverSocket.bind(('',serverPort)) # Listen to at most 1 connection at a time serverSocket.listen(1) # Server should be up and running and listening to the incoming connections while True: print('Ready to serve...') # Set up a new connection from the client connectionSocket, addr = serverSocket.accept() # If an exception occurs during the execution of try clause # the rest of the clause is skipped # If the exception type matches the word after except # the except clause is executed try: # Receives the request message from the client message = connectionSocket.recv(1024) # Extract the path of the requested object from the message # The path is the second part of HTTP header, identified by [1] filename = message.split()[1] # Because the extracted path of the HTTP request includes # a character '\', we read the path from the second character f = open(filename[1:],'rb') # Store the entire contenet of the requested file in a temporary buffer outputdata = f.read()#TODO replace with code to read file # Send the HTTP response header line to the connection socket #TODO-modify to send an encoded string connectionSocket.send("HTTP/1.1 200 OK "),connectionSocket.send(outputdata) # Send the content of the requested file to the connection socket for i in range(0, len(outputdata)): print(filename)   #TODO-send the ith outputdata encoded via the serverSocket connectionSocket.send(str.encode(outputdata[i])) connectionSocket.send(" ") # Close the client connection socket connectionSocket.close() except IOError: # Send HTTP response message for file not found connectionSocket.send("HTTP/1.1 404 Not Found ") connectionSocket.send("

404 Not Found

"
) # Close the client connection socket connectionSocket.close() serverSocket.close()

Thanks! :)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!