we're learning sockets in networking , we've been tasked fill out template in python (teacher's using python2.x while i'm using python3.x).
# import socket module socket import * # create tcp server socket #(af_inet used ipv4 protocols) #(sock_stream used tcp) serversocket = socket(af_inet, sock_stream) # assign port number serverport = 6789 # bind socket server address , server port serversocket.bind(('',serverport)) # listen @ 1 connection @ time serversocket.listen(1) # server should , running , listening incoming connections while true: print ("ready serve...") # set new connection client connectionsocket, addr = serversocket.accept() # if exception occurs during execution of try clause # rest of clause skipped # if exception type matches word after except # except clause executed try: # receive request message client message = connectionsocket.recv(4096).decode() # extract path of requested object message # path second part of http header, identified [1] filename = message.split()[1] # because extracted path of http request includes # character '\', read path second character f = open(filename[1:]) # store entire contenet of requested file in temporary buffer outputdata = f.read() # send http response header line connection socket connectionsocket.send(("http/1.1 200 ok \r\n").encode()) # send content of requested file connection socket in range(0, len(outputdata.encode())): connectionsocket.send(outputdata.encode()) connectionsocket.send(("\r\n").encode()) # close client connection socket connectionsocket.close() break except ioerror: # send http response message file not found connectionsocket.send(("http/1.1 404 not found\r\n").encode()) connectionsocket.send(("<html><head></head><body><h1>error. try again</h1></body></html>\r\n").encode()) # close client connection socket connectionsocket.close() break #close socket serversocket.close()
the file i'm reading .htm file:
<html><head><title>html test file</title></head><body><h1>trying frickin' program work</h1></body></html>
when run program , enter: localhost:6789/testfile.htm, prints file contents on , on , gives me error message: line 34, indexerror: list index out of range. edit: break takes care of error message, file still being printed on , over
what doing wrong?
edit #2: i'm trying error handling, merely states no data sent when type in file doesn't exist (i.e. localhost:6789/test.htm). how error message print?
in range(0, len(outputdata.encode())): connectionsocket.send(outputdata.encode())
this code:
- encodes text twice
- loops 121 times (which length of file posted, encoded ascii or utf-8)
- sends entire file each of 121 times
Comments
Post a Comment