Reputation:
I am trying to make a python web server with the Socket module. I am following this video https://www.youtube.com/watch?v=_najJkyK46g.
This is my code:
import socket
host = ''
port = 8000
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((host, port))
listen_socket.listen(1)
print("Listening on port "+str(port))
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024)
print(request)
http_response = "Hello World."
client_connection.sendall(bytes(http_response.encode('utf-8')))
client_connection.close()
When I go to chrome and enter 127.0.0.1:8000 it doesn't work. It brings up an error saying "This page isn't working". 127.0.0.1 sent an invalid response. ERR_INVALID_HTTP_RESPONSE. Please help me?
Upvotes: 3
Views: 772
Reputation: 55962
Chrome is expecting an HTTP response which is a structured protocol, which Hello World.
doesn't comply with:
https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Response_message
The response message consists of the following:
A status line which includes the status code and reason message (e.g., HTTP/1.1 200 OK, which indicates that the client's request succeeded). Response header fields (e.g., Content-Type: text/html). An empty line. An optional message body. The status line and other header fields must all end with . The empty line must consist of only and no other whitespace.[31] This strict requirement for is relaxed somewhat within message bodies for consistent use of other system linebreaks such as or alone.[33]
Updating to the following response should work:
HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Encoding: UTF-8
Content-Length: 138
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
ETag: "3f80f-1b6-3e1cb03b"
Accept-Ranges: bytes
Connection: close
<html>
<head>
<title>An Example Page</title>
</head>
<body>
Hello World, this is a very simple HTML document.
</body>
</html>
If you're going to be making a server to communicate over HTTP I would def recommend a python web http framework, of which there are many. Two very light weight ones being:
Upvotes: 2