Thursday, March 19, 2015

Python: A Static Server

My simple server had three requirements, listen to an address, parse information, and respond accordingly.

Challenge: Listen to an address
Solution: Initialize a socket to listen into my localhost

The first step was to import the socket class, and initialize a socket to the AF_INET family, and SOCK_STREAM type. This type is for the TCP sockets, and the AF_NET family sets up the socket object on the network by taking a two parameter tuple of host and port. The address was set to my localhost,, and the port was set to 8080. Port 80 is the default HTTP port, but it is only accessible by the root user, port 8080 is the designated HTTP alternate. The socket was then bound to the address and set to listen and establish a connection with incoming requests.

Challenge: Parse the incoming request
Solution: Use regular expressions to extract the method and path

Initially I thought all methods would be in capital letters and used the reg-ex code ^([A-Z]+) to collect and group one or more capital letters from the start of the string. Though looking into the documentation the request line only requires that the method token be followed by a space, and so the code was updated to,  ^([^ ]+) which instead looks for any character that is not a string. The path was then collected by grouping content until the next space was encountered, ... (^[^ ]). The final parameter of the request line is HTTP and the version, which I matched with ... HTTP.*$ . This looks for the letters HTTP followed by anything till the end of the line. Note: The original request data was split by \r\n, so the request line was an isolated string.

Challenge: Respond accordingly
Solution: Depending on the method, if the file requested exists, and its file type send response data

My server exclusively responded to GET method requests, if the condition was met the path was checked. My files were held inside a directory titled 'www' this path was defined in the global variable WEBROOT. Once WEBROOT was appended to the path I used os.path.isfile to check if a file existed. If the file was not found a page was returned alerting the user with the 404 error code. If it tested true I assigned a content type depending on the file extension at the end of the path, and saved the length of the files content.  The response data was then constructed with the content type and length added into the header, and the file appended as the body. This response data was send back over the connection.

No comments:

Post a Comment