This is my python socket http server:
# import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# Prepare a server socket
serverPort = 6789
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
while True:
# Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
print("addr:"+str(addr))
try:
message = connectionSocket.recv(4096).decode()
print(message)
filename = message.split()[1]
f = open(filename[1:])
content = f.read()
f.close()
print("200 OK")
outputdata = ("HTTP/1.1 200 OKrnConnection: closernContent-Length: " +
str(len(content)) +
"rnContent-Type: text/htmlrnrn" +
content)
# send the HTTP header line into socket
# send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send("rn".encode())
connectionSocket.close()
except FileNotFoundError:
# send response message for file not found
print("404 Not Found.")
errorMessage = "HTTP/1.1 404 Not FoundrnConnection: close"
for i in range(0, len(errorMessage)):
connectionSocket.send(errorMessage[i].encode())
connectionSocket.send("rn".encode())
connectionSocket.close()
print('End serve...')
serverSocket.close()
When I connect the server in Chrome, it works successfully.
And this is the output in console:
Ready to serve...
addr:('127.0.0.1', 57419)
GET /index.html HTTP/1.1
Host: localhost:6789
Connection: keep-alive
Cache-Control: max-age=0
sec-ch-ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: en-US,en;q=0.9
200 OK
End serve...
Ready to serve...
addr:('127.0.0.1', 57420)
However, at the end of the output, it shows that a new connection is established because the address is printed, but the server receive nothing so it block in message = connectionSocket.recv(4096).decode()
.
What’s more, this is index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgo=">
</head>
<body>
<h5>
Hello and Congratulations!
</h5>
</body>
</html>
I suppose that the browser connect to the server again but doesn’t send anything. I wonder why this happen and how to resolved it. Thanks for help.