mercredi 25 mars 2015

Python not sending all data, only 4kb

I am attempting to create a Python web server however it seems to not be able to send any files larger then 4KB. If the file is above 4KB in size it just cuts off the end of the text/image past 4KB. Anything embedded from other sources (Amazon S3/Twitter) work fine.


Here is the server code. It is a bit of a mess at the moment but I am focused on getting it to work. Afterwards I will add more security to the code.



'''
Simple socket server using threads
'''

import socket
import sys
import time
import os
from thread import *

HOST = '' # Symbolic name meaning all available interfaces
PORT = 80 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client

#infinite loop so that function do not terminate and thread do not end.
while True:

#Receiving from client
data = conn.recv(4096)
print data
dataSplit = data.split(' ')
print dataSplit

contentType = "text/html"

if(dataSplit[1].endswith(".html")):
print "HTML FILE DETECTED"
contentType = "text/html"
elif(dataSplit[1].endswith(".png")):
print "PNG FILE DETECTED"
contentType = "image/png"
elif(dataSplit[1].endswith(".css")):
print "CSS FILE DETECTED"
contentType = "text/css"
else:
print "NO MIMETYPE DEFINED"

conn.sendall('HTTP/1.1 200 OK\nServer: TestWebServ/0.0.1\nContent-Length: ' + str(os.path.getsize('index.html')) + '\nConnection: close\nContent-Type:' + contentType + '\n\n')

print '\n\n\n\n\n\n\n\n'

with open(dataSplit[1][1:]) as f:
fileText = f.read()
n = 1000
fileSplitToSend = [fileText[i:i+n] for i in range(0, len(fileText), n)]
for lineToSend in fileSplitToSend:
conn.sendall(lineToSend)
break

if not data:
break

#came out of loop
conn.close()

#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])

#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))

s.close


Thank you for your time.





Aucun commentaire:

Enregistrer un commentaire