通过python套接字发送文本"http"

Gop*_*a S 8 python browser sockets http response

我正在尝试使用python创建一个HTTP服务器.问题是除了发送响应消息之外,我正在努力工作; 如果消息有文本http,则send()不起作用.

这是代码的片段:

connectionSocket.send('HTTP/1.1 200 OK text/html')
Run Code Online (Sandbox Code Playgroud)

以下是我尝试的其他人:

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])
Run Code Online (Sandbox Code Playgroud)

似乎唯一有用的就是实体 - 在任何角色中扮演角色HTTP,比如

connectionSocket.send('HTTP/1.1 200 OK text/html')
Run Code Online (Sandbox Code Playgroud)

在哪里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();
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

hol*_*web 10

您没有返回正确形成的HTTP响应.你的路线

connectionSocket.send('HTTP/1.1 200 OK text/html') ## this is not working
Run Code Online (Sandbox Code Playgroud)

甚至没有换行符,然后紧接着你的文件内容.像HTTP这样的协议相当严格地指定了必须发送的内容,而且我发现你在浏览器中看到任何东西都有点奇迹.

尝试类似的东西:

connectionSocket.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
Run Code Online (Sandbox Code Playgroud)

这是具有主响应行和单个头的正确形成的HTTP 1.1响应的开始.双换行符终止标题,使客户端准备读取后面的内容.

http://www.jmarshall.com/easy/http/是学习更多关于您选择使用的协议的许多平易近人的方法之一.祝好运!