2014-01-10 72 views
0

我的代碼:蟒蛇3 HTTP插座不工作

import socket 

host = '' 
port = 8090 
backlog = 5 
size = 1024 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((host,port)) 
s.listen(backlog) 
while 1: 
    client, address = s.accept() 
    #data = client.recv(size) 


    data= "ok" 

    if data: 
     client.send(bytes('HTTP/1.0 200 OK<CRLF>', 'UTF-8')) 
     client.send(bytes("Content-Type: text/html<CRLF><CRLF>", 'UTF-8')) 
     client.send(bytes('<html><body><h1>Hello World</body></html>', 'UTF-8')) 
    client.close() 

由於某種原因,每當我訪問: HTTP:本地主機:8090谷歌瀏覽器的回報:

「的網頁在http:本地主機:8090威力暫時關閉,或者它可能永久移動到新的網址。「

我擡頭噸的例子,我不知道這是爲什麼不工作

我在Windows 7上運行的Python 3.3,三江源。

回答

0

你的<CRLF>字符在0123應該是\r\n。如果你然後把.recv回到它的工作原理:

import socket 

host = '' 
port = 8090 
backlog = 5 
size = 1024 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((host,port)) 
s.listen(backlog) 
while 1: 
    client, address = s.accept() 
    data = client.recv(size) 

    if data: 
     client.send(bytes('HTTP/1.0 200 OK\r\n', 'UTF-8')) 
     client.send(bytes("Content-Type: text/html\r\n\r\n", 'UTF-8')) 
     client.send(bytes('<html><body><h1>Hello World</body></html>', 'UTF-8')) 
    client.close() 

Python用反斜槓字符\在字符串逃脫。有關更多詳情,請參閱http://docs.python.org/2/reference/lexical_analysis.html#strings

+0

這工作!謝謝!! – user1564622