我已经在python中创建了一个服务器,并且在请求文件时试图将文件发送到客户端。服务器收到请求,但不能通过TCP发送文件。无法通过python通过HTTP(通过TCP)发送文件。我的代码有什么问题?
我使用了一个模板来创建一个响应头,然后我尝试发送该文件,但它并不完全工作。我能够“发送”.py和.html文件,而且它们在我的浏览器中显示,但它一定是运气,因为根据我的技术援助,真正的测试是图像...这不适合我。
首先,我将发布标题和响应,如Firefox插件Firebug,然后是我的代码,最后是错误消息。
Firebug的请求和响应
----------------------------
响应Headersview源
Accept-Ranges bytes
Connection Keep-Alive (or Connection: close)Content-Type: text/html; charset=ISO-8859-1
Content-Length 10000
Keep-Alive timeout=10, max=100
请求Headersview源
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Host xxx.xxx.244.5:10000
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
**我的Python代码:**
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a server socket
serverPort = 10000
serverName = 'xxx.xxx.xxx.xx' #Laptop IP
serverSocket.bind((serverName,serverPort))
serverSocket.listen(5)
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
print addr
try:
message = connectionSocket.recv(4096)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
f.close()
print 'length of output data: '
print len(outputdata)
print filename
print message
header = ("HTTP/1.1 200 OK\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Length: 100000\r\n"
"Keep-Alive: timeout=10, max=100\r\n"
"Connection: Keep-Alive\r\n (or Connection: close)"
"Content-Type: text/html; charset=ISO-8859-1\r\n"
"\r\n")
connectionSocket.send(header)
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.sendall(outputdata[i])
connectionSocket.close()
print '\ntry code has executed\n'
except IOError:
print 'exception code has been executed'
connectionSocket.send('HTTP/1.1 404 Not found: The requested document does not exist on this server.')
connectionSocket.send('If you can read this, then the exception code has run')
print '\tconnectionSocket.send has executed'
connectionSocket.close()
print '\tconnectionSocket.close has executed\n'
#serverSocket.close()
这里是错误消息:
此图片 “http://xxx.xxx.244.5:10000/kitty.jpg” 无法显示,因为它包含错误。
预先感谢您!
WOWOWOWOW !!!!这工作。我花了两天的时间试图找出这一个!模板代码(提供给我们修改的模板代码在我粘贴它时写下了这行代码,非常感谢!现在我将阅读python的文件处理过程......我想我没有经验来质疑模板。我在脚本中遇到了其他问题(如果我从客户端取消文件传输,服务器崩溃,但我会在今天晚些时候尝试解决这个问题)。您已经解决了我最大的问题! – newbie