Delivering HTML with Python Socket Server

I am currently learning about HTTP/CGI and exploring how to display HTML content on a webpage through the use of the socket library in Python. However, I am encountering some confusion regarding the correct syntax for this task:

#!/usr/bin/env python
import random
import socket
import time

s = socket.socket()         # Creating a socket object
host = socket.getfqdn() # Retrieving the local machine name
port = 9082
s.bind((host, port))        # Binding to the specified port

print 'Initiating server on', host, port
print 'The URL for accessing this Web server would be http://%s:%d/' % (host, port)

s.listen(5)                 # Waiting for client connection.

print 'Entering an infinite loop; press CTRL-C to exit'
while True:
    # Establishing connection with the client.   
    c, (client_host, client_port) = s.accept()
    print 'Connection established from', client_host, client_port
    c.send('Server Online\n')
    c.send('HTTP/1.0 200 OK\n')
    c.send('Content-Type: text/html\n')
    c.send(' """\
        <html>
        <body>
        <h1>Hello World</h1> This is my server!
        </body>
        </html>
        """ ')
    c.close()

The first three lines using "c.send" are functioning properly. However, when it comes to incorporating HTML code in the last line, I encountered a syntax error.

Answer №1

Here is an alternative code snippet:

def handle_client_request():
    while True:
        # Establish connection with the client.    
        connected_socket, (client_host, client_port) = server.accept()
        print 'Client connected from:', client_host, client_port
        
        connected_socket.recv(1000) # Receive request from the client (GET ....)
        
        # Prepare and send the HTTP response
        http_response = """HTTP/1.0 200 OK\nContent-Type: text/html\n\n<html>\n<body>\n<h1>Hello World</h1> This is my server!</body></html>\n"""
        connected_socket.send(http_response)

        connected_socket.close()

# Main function to start the server
if __name__ == '__main__':
    server_socket = create_server_socket() # Create a socket for the server
    handle_client_request() # Handle incoming client requests

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to display a div on top of a background image

Here is a visual representation of my design for better understanding: I am currently working on developing the central content that overlays the image. However, when I insert divs with background colors into my HTML to test their placement, I do not see ...

Creating CSS styles to ensure text takes up the largest size possible without wrapping or extending beyond the screen borders

Looking for a way to display text at its maximum size without any wrapping or overflowing the screen? I attempted using @media and adjusting font-size, but things got too complex. My goal is to have the text on example.com displayed at the largest possible ...

Is there a way to determine the number of lines in a CSV file in Python before loading

I recently started learning Python and I need to import dataframes from different CSV files. I have a specific business logic that relies on the number of rows in the CSV file. Is there a way for me to determine the total number of rows in a CSV file wit ...

Python script to extract data from a JSON file

Struggling to read data from a JSON file and display the values? Having trouble figuring out how to access all the values from the first dictionary in the list? Here's what you want to print: website: https://www.amazon.com/Apple-iPhone-GSM-Unlocke ...

Save picture in localStorage

Hello, I am currently working on a page where I need to retrieve an image from a JSON file and store it locally. Below is the code I have been using: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.10.1.min. ...

Accordion symbol for adding or subtracting

Looking for a way to change the Toggle text in my angular 7 application accordion to images or content displaying a + sign for collapse and - for expand. I need to achieve this using CSS in my SCSS stylesheet so that I can later change the color of the sig ...

Send form information using the REST method

Can someone provide guidance on how to properly handle this endpoint in my code? @PostMapping("/createUser") public ResponseEntity<User> createUser(@RequestBody User user) {...} I am looking to implement a user creation feature on my HTML ...

Error: The 'MainHandler' class does not contain a method named 'create_login_url'

I came across an issue while working with Google App Engine. I directly copied the code from the platform, but it didn't work as expected. The error message I kept receiving was: self.redirect(self.create_login_url(self.request.uri)) AttributeError: ...

Ways to create mobility for IIWA

We are developing a simulation for a robot that is tasked with navigating through a grocery store to pick up items for online orders. In order to accomplish this, we need to modify the IIWA robot to have mobility rather than being fixed in place. We are se ...

Can I choose multiple rows at once in a treeview widget?

Can you select multiple rows in a treeview widget and how do you retrieve the selected rows? I've created a treeview, but I can't seem to figure out how to select multiple rows at once. https://i.stack.imgur.com/lH43J.png If selecting multiple ...

Creating my website with a unique inverse color scheme

I'm looking to change the color scheme of my webpage so that it is inverse (white becomes black and black becomes white) similar to the Dark Reader chrome extension: https://chrome.google.com/webstore/detail/dark-reader/eimadpbcbfnmbkopoojfekhnkhdbiee ...

Angular 9 - Auto-adjust the height of the text box as the user types, returning to its original size when no longer in focus

I need a solution where an input field's height adjusts to display the user's entry, then returns to normal size when they click away. It should function similar to this example image: https://i.stack.imgur.com/yKcik.png Once the user enters th ...

Using JavaScript, redirect to a specified URL once a valid password has been entered on an HTML form

Need help with JavaScript for password validation and URL redirection. I'm new to JS and used some resources like Password correct? then redirect & Adding an onclick function to go to url in javascript?. Here's my current code: ...

problem encountered when trying to convert dtype('O') to a date format

Hey there, I'm encountering an issue with dates in my raw dataset (under the column name 'earliest_cr_line'). When I checked the dtype on Jupyter, it showed as dtype('O'). In order to convert it to a datetime format, I used the cod ...

Utilize Python (specifically with the Pillow library) to remove transparent backgrounds

When using the python module html2image to convert html to an image, I encountered an issue with fixed image size causing the html to break or get cut off, leaving a blank space. Is there a Python-based solution to fix this problem? (I am using chat export ...

Ways to incorporate varying point sizes in a ScatterPlotly Graph Object depending on tuple values

I am currently working on creating a network graph with the help of networkx. The graph is constructed using data from a pandas data frame, shown below: source target weight 0 8386 9205 2 1 9205 8386 5 2 9205 280159 1 3 9205 ...

Are `<text>` nodes unable to utilize ligature fonts in CSS/SVG?

Check out this JsFiddle demo: http://jsfiddle.net/d0t3yggb/ <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <div class="material-icons">add add add add</div> <svg width="100%" height="100% ...

Problem with CSS creating the Typewriter effect when the third line of text is added

I've been working on a website for my new company and I want to incorporate a typewriter effect on the main page. I came across a tutorial on Medium.com but I'm having trouble adding an additional span to the provided code. Take a look at the lin ...

Use JavaScript to illuminate individual words on a webpage in sequence

Is there an effective method to sequentially highlight each word on a web page? I'm thinking of breaking the words into an array and iterating through them, but I'm not sure what the best approach would be. I have experience with string replacem ...

How can I position a vertically centered image to the left of a block paragraph using inline styles?

I am faced with the challenge of aligning a 100x100 vertically-centered image to the left of a text block that extends beyond its height. It is important that the text does not wrap underneath the image but stays in a single block on the right side. I must ...