无法从HTTP Web服务器

时间:2015-05-31 02:09:41

标签: python sockets webserver

当我在python脚本下运行并尝试通过safari对.html文件进行GET请求时,我会获得原始格式的内容,即HTML标签。如何检索html页面,如果我对图像进行GET,则说文件已损坏。

from socket import *    
serverSocket = socket(AF_INET, SOCK_STREAM)     #create a socket

serverPort = 7000  
serverSocket.bind(('',serverPort))  
serverSocket.listen(1)

while True:    

    print 'Ready to serve . . .'
    connectionSocket, addr = serverSocket.accept()  #create socket for client
    try:
        message =connectionSocket.recv(1024)   #receive message from client
        print message
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata =f.read()
        #Send HTTP header line into socket
        connectionSocket.send('\nHTTP/1.x 200 OK\n')
        #Send contents of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i])
        connectionSocket.close()
        print 'File Received'
    except IOError:
        connectionSocket.send('\n404 File Not Found\n')
        connectionSocket.close()
serverSocket.close()

1 个答案:

答案 0 :(得分:0)

您需要告诉客户端您正在发送HTML。在发送数据之前添加:

connectionSocket.send("Content-type: text/html\r\n")

此外,您可能会看到您正在发回的HTTP响应标头,对吧?如果是这样,那是因为你有一个前导\n,它终止了标题并使得被发回的身体的其余部分,所以将该行更改为

connectionSocket.send('HTTP/1.x 200 OK\r\n')

并确保在完成所有标题后添加一个空行,并且HTTP中的行尾应该是\r\n而不仅仅是\n尽管我不会感到惊讶浏览器只用\n

处理它