Python client/server that reads HTML body from server

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
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?
 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
It seems like you have a small mistake in your server code. You have placed the serverSocket.close() and sys.exit() statements inside the while True loop. This means that the server socket will be closed and the program will exit after serving the first request. You should move these statements outside the loop so that the server continues to listen for new connections after serving a request.
After correcting this mistake, you should be able to access the HTML file via the URL
http://127.0.0.1:6789/HelloWorld.html in your browser.

Here's the corrected server code:
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()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,708
Latest member
SherleneF1

Latest Threads

Top