我正在尝试使用python创建HTTP服务器。关键是我要使所有工作正常,除了发送响应消息。如果邮件中包含文字http
,send()
则无法使用。
这是代码片段:
connectionSocket.send('HTTP/1.1 200 OK text/html')
这是我尝试过的其他人:
connectionSocket.send(''.join('%s 200 OK text/html' % ('HTTP/1.1')))
connectionSocket.send('%s 200 OK text/html' % ('HTTP/1.1'))
msg = 'HTTP/1.1 200 OK text/html'
for i in range(0, len(msg))
connectionSocket.send(msg[i])
似乎唯一有效的方法是将实体中的任何字符实体化HTTP
,例如
connectionSocket.send('HTTP/1.1 200 OK text/html')
哪里H
等于H
。否则,浏览器将不会显示从python服务器套接字接收到的标头。
当我尝试发送404 Message
套接字时,该问题也会出现。但是,显示其他内容,就像通过套接字发送的html文件一样。
我想知道是否有适当的方法?因为,如果客户端不是浏览器,则无法理解html实体。
提前致谢
更新:
码:
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(('127.0.0.1', 1240))
serverSocket.listen(1);
while True:
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Send one HTTP header line into socket
connectionSocket.send('HTTP/1.1 200 OK text/html') ## this is not working
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
connectionSocket.send('HTTP/1.1 404 File not found') ## this is not working
connectionSocket.close();
serverSocket.close()
屏幕截图:
文字为“ HTTP / 1.1 ...”
文字为“ HTTP / 1.1 ...”
hello.html的HTML代码
<html>
<head>
<title>Test Python</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
您没有返回正确格式的HTTP响应。你的线
connectionSocket.send('HTTP/1.1 200 OK text/html') ## this is not working
甚至不会以换行符终止,而是紧随其后的是文件内容。像HTTP这样的协议相当严格地指定了必须发送的内容,而且我发现您在浏览器中看到的所有内容几乎没有什么奇迹。
尝试类似:
connectionSocket.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
这是带有主响应行和单个标头的格式正确的HTTP 1.1响应的开始。双换行符终止标头,为客户端准备读取随后的内容。
http://www.jmarshall.com/easy/http/是许多可学的方法之一,可以更多地了解您选择使用的协议。祝好运!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句