- Joined
- Apr 12, 2023
- Messages
- 1
- Reaction score
- 0
I am writing a very simple Python socket program to read an HTML body from a server. If I create a HelloWorld.html file and open it with the specified host and port, I can open the file in my browser with the following server and read the information in the HTML file. However, I failed to open the webpage by trying to access it through http://127.0.0.1:6789/HelloWorld.html.
Server
Client
I tried to open this HTML file in the browser via URL: http://127.0.0.1:6789/HelloWorld.html. If I remove the "6789" or change it to a different port number, I get a "404 not found" error code.
My server code and client code are both in the same directory, and Helloworld.html is also here. Can you tell me why I am unable to open the HTML file in the server via URL?
Server
Python:
from socket import *
import sys
serverSocket = socket(AF_INET, SOCK_STREAM)
host = '127.0.0.1'
port = 6789
serverSocket.bind((host, port))
serverSocket.listen(5)
print('The TCP server is ready to receive')
while True:
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024).decode()
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
response_headers = "HTTP/1.1 200 OK\r\n"
response_headers += "Content-Type: text/html\r\n"
response_headers += "Content-Length: %d\r\n" % len(outputdata)
response_headers += "\r\n"
connectionSocket.send(response_headers.encode())
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.close()
except IOError:
response_headers = "HTTP/1.1 404 Not Found\r\n"
response_headers += "Content-Type: text/html; charset=UTF-8\r\n"
response_headers += "\r\n"
response_body = "<html><body><hl>404 Not Found</h1></body></html>"
connectionSocket.send((response_headers + response_body).encode())
connectionSocket.close()
serverSocket.close()
sys.exit()
Client
Python:
from socket import *
serverName = '127.0.0.1'
serverPort = 6789
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
message = 'GET /HelloWorld.html HTTP/1.1\r\nHost: 127.0.0.1:6789\r\n\r\n'
clientSocket.send(message.encode())
response = b''
while True:
data = clientSocket.recv(1024)
if not data:
break
response += data
print(response.decode())
clientSocket.close()
I tried to open this HTML file in the browser via URL: http://127.0.0.1:6789/HelloWorld.html. If I remove the "6789" or change it to a different port number, I get a "404 not found" error code.
My server code and client code are both in the same directory, and Helloworld.html is also here. Can you tell me why I am unable to open the HTML file in the server via URL?