【发布时间】:2014-03-31 18:12:19
【问题描述】:
我正在尝试使用 python 创建一个 HTTP 服务器。问题是除了发送响应消息外,我正在让一切正常工作;如果消息中有文字http,则send() 不起作用。
这里是sn-p的代码:
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是socket无法发送问题的根源。 -
@PauloBu 这是我首先想到的,但是,其他元素显示正确。代码发送从文件中读取的 html 数据,浏览器正常显示,除了 http 头。
-
但是浏览器不应该显示http头不是吗?
-
请提供足够的信息来重现问题。告诉我们您正在使用哪些库等。
-
有效的 HTTP 被浏览器剥离 - 这就是浏览器与服务器通信的方式。如果您看到呈现的 html,那么它可能正在工作
标签: python sockets http browser response