我正在尝试创建一个Python Web服务器,但它似乎无法发送任何大于4KB的文件。如果文件大小超过4KB,则只会将文本/图像的末尾切断4KB。从其他来源(亚马逊S3 / Twitter)嵌入的任何东西都可以正常工作。
这是服务器代码。目前这有点乱,但我专注于让它发挥作用。之后我会为代码添加更多安全性。
'''
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
感谢您的时间。
答案 0 :(得分:0)
所以,谢谢你的用户“你”我们发现了这个问题。我有这个代码:
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')
代替此代码:
conn.sendall('HTTP/1.1 200 OK\nServer: TestWebServ/0.0.1\nContent-Length: ' + str(os.path.getsize(dataSplit[1][1:])) + '\nConnection: close\nContent-Type:' + contentType + '\n\n')
问题在于我为每个文件发送了index.html的文件大小,因此Chrome和其他浏览器只删除了额外的数据。事实上,index.html是4KB所以我虽然这是一个数据包限制或该领域的东西。