Having trouble with a simple server written by python

This is a simple server. When you open the browser type in the server address, it will respond to the status code and the contents of the requested html. But when I add this sentence "connectionSocket.send (" HTTP / 1.1 200 OK "), nothing is returned. When I deleted it, returned html. And another problem is when I send the request with a web browser to the server two connections are sent, and one of them wants to find a file called favicon.ico, but of course it is IOError, because it doesnโ€™t have such a file on it. my server root directory. The code is attached and thanks for the help.

 #import socket module from socket import * serverSocket = socket (AF_INET, SOCK_STREAM) #prepare a server socket serverSocket.bind (('192.168.0.101', 8765)) serverSocket.listen (1) while True: #Establish the connection print ' Ready to serve ... 'connectionSocket, addr = serverSocket.accept () print' connected from ', addr try: message = connectionSocket.recv (1024) filename = message.split () [1] print filename f = open (filename [1:]) outputdata = f.read () #Send one HTTP header line into socket # connectionSocket.send ('HTTP / 1.1 200 OK') #Send the content of the requested file to the client for i in range (0 , len (outputdata)): connectionSocket.send (outputdata [i]) connectionSocket.close () except IOError: print 'IOError' #Send response message for file not found connectionSocket.send ('file not found') #Close Client socket connectionSocket.close () serverSocket.close () 
+4
source share
2 answers

You need to add to the new lines ( \r\n\r\n ) at the end of the HTTP headers:

 connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n') 

Also, you should probably use a higher level library to write your HTTP server ...

+5
source

You tried to convert the return value from string to bytes

Replace this:

 connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n') 

With the help of this

 connectionSocket.send(bytes('HTTP/1.1 200 OK\r\n\r\n','UTF-8')) 
0
source

All Articles