2011-11-29 59 views
7

我已经设置了一个小脚本,应该使用html为客户端提供支持。使用python发送http标头

import socket 

sock = socket.socket() 
sock.bind(('', 8080)) 
sock.listen(5) 
client, adress = sock.accept() 


print "Incoming:", adress 
print client.recv(1024) 
print 

client.send("Content-Type: text/html\n\n") 
client.send('<html><body></body></html>') 

print "Answering ..." 
print "Finished." 

import os 
os.system("pause") 

但它显示在浏览器的纯文本。你能告诉我需要做什么吗?我只是找不到帮助我的谷歌的东西..

谢谢。

回答

13

响应头应包含一个表示成功的响应代码。 的的Content-Type线之前,添加:

client.send('HTTP/1.0 200 OK\r\n') 

此外,为了使测试更加明显,放于页面的一些内容:

client.send('<html><body><h1>Hello World</body></html>') 

响应后发送,关闭

client.close() 

0123:带连接

正如其他海报已经注意到,终止每行\r\n而不是\n

那些补充,我能够运行成功的测试。在浏览器中,我输入了localhost:8080

这里的所有代码:

import socket 

sock = socket.socket() 
sock.bind(('', 8080)) 
sock.listen(5) 
client, adress = sock.accept() 

print "Incoming:", adress 
print client.recv(1024) 
print 

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

print "Answering ..." 
print "Finished." 

sock.close() 
+1

...不要忘记,以取代\ n \ n转换为\ r \ n \ r \ n,因为HTTP需要在头后发送CRLF。 – werewindle

+0

并更好地使用'\ r \ n \ r \ n'代替'\ n \ n' – dmitry

+0

哇,那就是它。谢谢 !使用http协议有没有关于服务器和客户端交换的相关文档? –

0

webob做肮脏的HTTP细节对你来说也是

from webob import Response 
.... 

client.send(str(Response("<html><body></body></html>"))) 
+0

请注意,webob使用'\ n'分隔行而不是正确的'\ r \ n'。这是[#146](https://github.com/Pylons/webob/pull/146)。虽然浏览器似乎并不在意,所以在大多数情况下,您的解决方案都可以正常工作。 –

相关问题