kshama kshama - 1 year ago 236
Python Question

Python Web Server socket

I have to create a web server in Python. Below is the code I am working on. When i execute it, I initially get no error and it prints "Ready to serve.." , but after opening a browser and running (HelloWorld is an html file in the same folder as my python code, while is my IP address and 50997) is the server port), I get a TypeError saying 'a bytes like object is required and not str". please help me in resolving this and kindly let me know if any other modifications are required.

#Import socket module
from socket import *

#Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)

# Assign a port number
serverPort = 50997

serverSocket = socket(AF_INET, SOCK_STREAM)

#serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#print ("hostname is: "), gethostname()
#print ("hostname is: "), socket.gethostname()

# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))

# Listen to at most 1 connection at a time

# 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()

# Receives the request message from the client
message = connectionSocket.recv(1024)
print ("Message is: "), message

filename = message.split()[1]
print ("File name is: "), filename

f = open(filename[1:])

outputdata = f.read()
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")

for i in range(0, len(outputdata)):

# Close the client connection socket

except IOError:
# Send HTTP response message for file not found
connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n")
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n")
# Close the client connection socket


The error I am exacly getting-

Ready to serve...
Message is:
File name is:
Traceback (most recent call last):
File "intro.py", line 56, in <module>
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
TypeError: a bytes-like object is required, not 'str'

Answer Source

You need to convert the string you are sending into bytes, using a text format. A good text format to use is UTF-8. You can implement this conversion like so:

bytes(string_to_convert, 'UTF-8')

or, in the context of your code:

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"))`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download