通过python s发送文本“http”

2024-10-06 20:28:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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();

服务器套接字。关闭()

截图:

文本为“HTTP/1.1…”

enter image description here

enter image description here

文本为“HTTP/1.1…”

enter image description here

enter image description here

hello.HTML的HTML代码

<html>
  <head>
    <title>Test Python</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>

Tags: 方法代码text文本服务器sendhttphtml
2条回答

您没有返回格式正确的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/是了解您选择使用的协议的许多可接近的方法之一。祝你好运!

我不确定您正在使用什么connectionSocket(哪个模块、库等),但是如果这个东西已经是与HTTP相关的例程的一部分,那么很可能它已经发送了必要的HTTP行,而您却没有这样做。那么你的可能会扰乱这个过程。

浏览器中的HTTP协议可能无法识别引用的版本(&#72;TTP…)(我认为引用只能在OSI堆栈的更高层中识别和解释),因此没有相同的效果。

相关问题 更多 >