Gopikrishna S Gopikrishna S - 22 days ago 8x
Python Question

Send text "http" over python socket

I am trying to create a HTTP server using python. The thing is I am getting everything to work except for sending a response message; if the message has a text

, the
doesn't work.

Here is the snippet of the code:

connectionSocket.send('HTTP/1.1 200 OK text/html')

Here are the others I tried:

connectionSocket.send(''.join('%s 200 OK text/html' % ('HTTP/1.1')))
connectionSocket.send('%s 200 OK text/html' % ('HTTP/1.1'))
msg = 'HTTP/1.1 200 OK text/html'
for i in range(0, len(msg))

The only thing that seems to work is entity-fying the any of the character in
, like

connectionSocket.send('HTTP/1.1 200 OK text/html')

is equivalent to
. Otherwise the browser doesn't display the header received from the python server socket.

The problem also goes when I am trying to send a
404 Message
down the socket. The other contents are displayed, however, like a html file sent through the socket.

I want to know is there a proper way to do it? Because, if the client is not a browser, the html entity will not be understood.

Thanks in advance



from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)

serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(('', 1240))

while True:
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata =

#Send one HTTP header line into socket
connectionSocket.send('HTTP/1.1 200 OK text/html') ## this is not working

#Send the content of the requested file to the client
for i in range(0, len(outputdata)):

except IOError:
connectionSocket.send('HTTP/1.1 404 File not found') ## this is not working



Text as 'HTTP/1.1 ...'

enter image description here

enter image description here

Text as 'HTTP/1.1 ...'

enter image description here

enter image description here

HTML Code of hello.html

<title>Test Python</title>
<h1>Hello World!</h1>


You are not returning a correctly formed HTTP response. Your line

connectionSocket.send('HTTP/1.1 200 OK text/html') ## this is not working

is not even terminated by a newline, then immediately followed by the content of your file. Protocols like HTTP specify fairly rigorously what must be sent, and I find it little short of miraculous that you saw anything at all in your browser.

Try something like:

connectionSocket.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n')

This is the start of a correctly-formed HTTP 1.1 response with a primary response line and a single header. The double newline terminates the headers, preparing the client to read the content that follows. is one of many approachable ways to learn a bit more about the protocol you have chosen to use. Good luck!