Simple python TCP server help

sweenish

Diamond Member
May 21, 2013
3,656
60
91
I'm in an interesting boat with a class. It's a network class, so we're learning all about that stuff. What is a little weird is that I was expected to "just know" python, but not just "just know" it. I also have to have a pretty good working of the socket library. Well, I don't.

We're supposed to build a simple TCP server that returns a single web page when requested, and a 404 for anything else.

I'm testing this using a VM running Debian 8 and the browser is Iceweasel (Firefox).

Here's the code:
Code:
# Import socket module
from socket import * 

# Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)
serverSocket = socket(AF_INET, SOCK_STREAM) 

# Assign a port number
serverPort = 6789

# Bind the socket to server address and server port
serverSocket.bind(('',serverPort)) 

# Listen to at most 1 connection at a time
serverSocket.listen(1) 

# Server should be up and running and listening to the incoming connections
while True:
    print 'Ready to serve...'
    
    # Set up a new connection from the client
    connectionSocket, addr = serverSocket.accept()
    
    # If an exception occurs during the execution of try clause
    # the rest of the clause is skipped
    # If the exception type matches the word after except
    # the except clause is executed
    try:
        # Receive the request message from the client
        message = connectionSocket.recv(1024)
        # Extract the path of the requested object from the message
        # The path is the second part of HTTP header, identified by [1]
        filename = message.split()[1]
        # Because the extracted path of the HTTP request includes 
        # a character '\', we read the path from the second character 
        f = open(filename[1:])
        # Store the entire contenet of the requested file in a temporary buffer
        outputdata = f.read()
        # Send the HTTP response header line to the connection socket
        connectionSocket.send("SITEHEADER")
 
        # Send the content of the requested file to the connection socket
        for i in range(0, len(outputdata)):  
            connectionSocket.send(outputdata)    
        break
        
        # Close the client connection socket
        connectionSocket.close() 

    except IOError:
        # Send HTTP response message for file not found
        connectionSocket.send("404HEADER")
        connectionSocket.send("<html><head></head><body><h1>404 FILE NOT FOUND</h1></body></html>\r\n")
        # Close the client connection socket
        connectionSocket.close()

#Close the Socket
serverSocket.close()
Most of the stuff in the while loop was given to me, and the comments serve as a guide. So the professor isn't being overly mean.

This is my process, and my problems:
1. run server using 'python WebServerTemplate.py'
2. Open new tab in browser and navigate to 'localhost:6789/index.html'
3. The problems are two-fold, here.

a. My raw html is shown, tags and all, as is the header
b. It is repeated many times (over a hundred)

4. Or, instead of navigating to index.html, I will test the error code with main.html
5. I get the proper error, but again, the raw html is shown and not rendered, and the header is printed.

Here's my html for completeness:
Code:
<!DOCTYPE html>
<html>
<head>
    <title>HI FRIEND</title>
</head>
<body>
    <h1>Hello World!</h1>
</body>
</html>
It's basically taken directly from w3scools as a very basic web site.

I feel like the problems I'm having are simple (pretty sure my for loop is to blame for the repition, but that loop line was given to me), but I only know the most basic python right now, and I'm trying to go off my textbook and notes to use the socket library, neither of which deal with an actual web page, just messages. Any assistance is greatly appreciated.
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,595
4,498
75
a. My raw html is shown, tags and all, as is the header
I'm quite certain the header you need to send is neither "SITEHEADER" nor "404HEADER". Try Firebug's Net toolbar, on a site such as this one, to see some valid headers. Chrome probably does something similar.

b. It is repeated many times (over a hundred)
What programming construct causes things to repeat? That should give you a clue.
 

sweenish

Diamond Member
May 21, 2013
3,656
60
91
Yeah, my headers were way off. That part is fixed, and the pages are now rendered properly.

I know that my for loop is likely the culprit, but I was given that line, for blah: in the template. I figured I needed to keep it. But commenting it out and adjusting whitespace did fix the problem.

Thanks for the guidance, I really appreciate that you guys take the time to help, especially with my piddly stuff.
 

sweenish

Diamond Member
May 21, 2013
3,656
60
91
It makes sense that the assignment has already been considered at a higher level.

The object of the lesson was more to see the handshaking and headers in code, as opposed to actually serving something.
 
Feb 25, 2011
16,988
1,619
126
Yeah, my headers were way off. That part is fixed, and the pages are now rendered properly.

I know that my for loop is likely the culprit, but I was given that line, for blah: in the template. I figured I needed to keep it. But commenting it out and adjusting whitespace did fix the problem.

Thanks for the guidance, I really appreciate that you guys take the time to help, especially with my piddly stuff.

Oh, I see the problem.

With your "for i in range()" statement, double check that you're iterating through something meaningful. It looks to me like you're iterating over a string:

http://stackoverflow.com/questions/538346/iterating-over-a-string

Which is, I'm thinking, NOT what you want to be doing.

When your professor gave you the metacode, they probably meant "for blah" as in "for each open connection/client".