Title | Server - This is the COMPLETED socket programming assignment. All the blanks have been |
---|---|
Course | Network Fundamentals |
Institution | University of Technology Sydney |
Pages | 1 |
File Size | 26.5 KB |
File Type | |
Total Downloads | 82 |
Total Views | 137 |
This is the COMPLETED socket programming assignment. All the blanks have been filled out and this is fully functional. All you have to do is copy and paste it into a text document, then convert that into a .py file...
#import socket module! from socket import *! import sys # In order to terminate the program! serverSocket = socket(AF_INET, SOCK_STREAM)! # Prepare a sever socket! # Assign a port number! serverPort = 8000! serverSocket.bind(('', serverPort)) # get and bind server address to port number! serverSocket.listen(1)! while True:! print('Ready to serve...')! connectionSocket, addr = serverSocket.accept() #establish the connection! try:! message = connectionSocket.recv(1024) #receives the request message from the client ! print 'Message is: ', message! filename = message.split()[1] #extract the second part of HTTP header identified by [1]! f = open(filename[1:]) # because the second part of the HTTP header includes a '/', this instructs to read from the second character expressed through '[1:]' ! outputdata = f.read() #store the entire content of the requested file in a temporary buffer connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n'.encode()) #Send a HTTP header line ! ! ! for i in range(0, len(outputdata)): #send content to client connectionSocket.send(outputdata[i].encode())! connectionSocket.send("\r\n".encode()) ! connectionSocket.close()! ! except IOError:! connectionSocket.send('HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n404 Not Found ☹')! connectionSocket.close() ! ! serverSocket.close()! connectionSocket.close()! sys.exit() #Terminate the program after sending the corresponding data !...