0

我在 python 中创建了一个服务器,并在请求文件时尝试将文件发送到客户端。服务器收到请求,但是我无法通过 TCP 发送文件。

我使用模板创建响应头,然后尝试发送文件,但它并不完全有效。我能够“发送” .py 和 .html 文件,它们确实显示在我的浏览器中,但这一定是运气,因为根据我的助教,真正的测试是图像......这对我不起作用。

首先,我将发布 Firefox 插件 Firebug 显示的标题和响应,然后是我的代码,最后是错误消息。

Firebug 请求和响应

----------------------------

响应标头view source

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

请求标头view source

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 ”无法显示,因为它包含错误。

先感谢您!

4

1 回答 1

2

以二进制模式打开您的 JPEG 文件:open(filename[1:], "rb"). 否则 Python 会帮助将文件中的某些字节转换为\n字符,这会损坏图像并阻止浏览器理解它。

此外,您应该使用 a Content-Typeofimage/jpeg来表示 JPEG 图像,而不是text/html,尽管您的浏览器似乎已经发现它无论如何都是 JPEG。

于 2013-10-27T19:17:45.410 回答