我已经建立了一个小脚本,该脚本应该为html提供客户端.
I've set up a little script that should feed a client with html.
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")但是它在浏览器中显示为纯文本.你能告诉我我需要做什么吗?我只是在Google中找不到对我有帮助的东西.
But it is shown as plain text in the browser. Can you please tell what I need to do ? I just can't find something in google that helps me..
谢谢.
推荐答案响应头应包含指示成功的响应代码.在 Content-Type 行之前,添加:
The response header should include a response code indicating success. Before the Content-Type line, add:
client.send('HTTP/1.0 200 OK\r\n')此外,要使测试更加可见,请在页面中放置一些内容:
Also, to make the test more visible, put some content in the page:
client.send('<html><body><h1>Hello World</body></html>')发送响应后,使用以下命令关闭连接:
After the response is sent, close the connection with:
client.close()和
sock.close()正如其他张贴者所指出的那样,以 \ r \ n 而不是 \ n 结束每一行.
As the other posters have noted, terminate each line with \r\n instead of \n.
通过这些添加,我可以运行成功的测试.在浏览器中,我输入了 localhost:8080 .
Will those additions, I was able to run successful test. In the browser, I entered 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()更多推荐
使用python发送HTTP标头
发布评论