Python Socket Server发送文件请求3次而不是一次?

时间:2014-10-12 21:07:14

标签: python html sockets python-2.7

使用套接字创建一个简单的python Web服务器,开始了解它们是如何工作的,但我想我已经迷失了。
我的python服务器应该访问同一目录中的基本html文件,并在每次请求时显示一次。但是这段代码由于某种原因发送请求3到5次......

from socket import *
server = socket(AF_INET, SOCK_STREAM)
port = 12030
server.bind((gethostname(), port))
server.listen(1)
while True:
    print 'Ready to serve'
    conection,  addr = server.accept()
    try:
        print 'Working'
        message = conection.recv(1024)
        filename = message.split()[1] #cuts off the '/' in the request page
        f = open(filename[1:])
        print message
        outputdata = f.read()
        print outputdata
        conection.send('HTTP/1.1 200 OK\r\n')
        for i in range(0, len(outputdata)):
            conection.send(outputdata[i])
        conection.close()
    except IOError:
        print 'IO ERROR'
        print message
        print outputdata
        conection.close()
    except KeyboardInterrupt:
        server.close()
        conection.close()
        break;

这是我在浏览器中打开页面的输出。

-en 14:59:54  @ ・ー ・ 
python project.py 
Ready to serve
Working
<html><body><h1>Wurld</body></html>

Ready to serve
Working
IO ERROR
<html><body><h1>Wurld</body></html>

Ready to serve
Working
IO ERROR
<html><body><h1>Wurld</body></html>

Ready to serve

我尝试添加server.listen(1)conection.send("Content-Type:text/html\r\n"),但这些都没有做任何事情。 除了阻止每分钟可以请求多少次之外,我不确定问题是什么?

每次更新以打印消息

-en 15:33:26  @ ・ー ・ 
python project.py 
Ready to serve
Working
GET /HelloWorld.html HTTP/1.1
Host: seppala:12030
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
DNT: 1
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8


<html><body><h1>Wurld</body></html>

Ready to serve
Working
IO ERROR
GET /favicon.ico HTTP/1.1
Host: seppala:12030
Connection: keep-alive
Accept: */*
DNT: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8


<html><body><h1>Wurld</body></html>

Ready to serve
Working
IO ERROR
GET /favicon.ico HTTP/1.1
Host: seppala:12030
Connection: keep-alive
Accept: */*
DNT: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8


<html><body><h1>Wurld</body></html>

Ready to serve

1 个答案:

答案 0 :(得分:1)

您的浏览器似乎正在请求favicon.ico。尝试将favicon.ico添加到您的文档根目录,或者尝试使用其他浏览器。这个问题不是因为你的脚本。