我用python创建了一个服务器,并试图在请求文件时将文件发送到客户机。服务器收到请求,但我无法通过TCP发送文件。在
我使用了一个模板来创建一个响应头,然后我尝试在之后发送该文件,但它并不完全有效。我可以“发送”.py和.html文件,它们确实会显示在我的浏览器中,但这一定是幸运的,因为根据我的助教,真正的测试是图像。。。这对我不起作用。在
首先,我将发布Firefox插件Firebug显示的头和响应,然后是我的代码,最后是错误消息。在
Firebug请求和响应
-----------------------------
响应标题查看来源
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
请求标题查看源
^{pr2}$**我的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”,因为它包含错误。在
提前谢谢!
以二进制模式打开JPEG文件:
open(filename[1:], "rb")
。否则Python将有助于将文件中的一些字节转换为\n
字符,这将损坏图像并阻止浏览器理解它。在另外,对于JPEG图像,您应该使用},尽管您的浏览器似乎已经发现它是JPEG。在
Content-Type
的image/jpeg
,而不是{相关问题 更多 >
编程相关推荐