I decided to make this work in Python 3 and make it work on Chrome as an example for the online course that I am developing. Python 3, of course, needs encode()
and decode()
in the right places. Chrome - really wants to send its GET request before it receives data. I also added some error checking so that it clears its socket if you interrupt the server or it explodes:
def createServer(): serversocket = socket(AF_INET, SOCK_STREAM) try : serversocket.bind(('localhost',9000)) serversocket.listen(5) while(1): (clientsocket, address) = serversocket.accept() rd = clientsocket.recv(5000).decode() pieces = rd.split("\n") if ( len(pieces) > 0 ) : print(pieces[0]) data = "HTTP/1.1 200 OK\r\n" data += "Content-Type: text/html; charset=utf-8\r\n" data += "\r\n" data += "<html><body>Hello World</body></html>\r\n\r\n" clientsocket.sendall(data.encode()) clientsocket.shutdown(SHUT_WR) except KeyboardInterrupt : print("\nShutting down...\n"); except Exception as exc : print("Error:\n"); print(exc) serversocket.close() print('Access http://localhost:9000') createServer()
The server also prints an incoming HTTP request. The code, of course, sends only text / html regardless of the request - even if the browser requests an icon:
$ python3 server.py Access http://localhost:9000 GET / HTTP/1.1 GET /favicon.ico HTTP/1.1 ^C Shutting down...
But this is a pretty good example that basically shows why you want to use a framework like Flask or DJango, instead of writing your own. Thanks for the source code.
source share