python web服务器response()输出的问题

看完Ruslan的Blog:

《Let’s Build A Web Server. Part 1.》

文章讲得很透,给出服务器代码为:

import socket

HOST, PORT = '', 8888

listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print 'Serving HTTP on port %s ...' % PORT
while True:
    client_connection, client_address = listen_socket.accept()
    request = client_connection.recv(1024)
# what is request? 
    print request

    http_response = """\
HTTP/1.1 200 OK

Hello, World!
"""
    client_connection.sendall(http_response)
    client_connection.close()

存储为webserver.py,在cmd命令行中运行:

c:\Python27>python.exe webserver1.py
Serving HTTP on port 8888 ...

说明web服务器正常启动。

在web浏览器中输入:

http://localhost:8888/

得到结果为:
python web服务器response()输出的问题_第1张图片

为什么代码明明是输出:

    http_response = """\
HTTP/1.1 200 OK

Hello, World!
"""

输出却只有:

Hello, World!

?????

原文解释:

“Let’s dissect it. The response consists of a status line HTTP/1.1 200 OK, followed by a required empty line, and then the HTTP response body.

The response status line HTTP/1.1 200 OK consists of the HTTP Version, the HTTP status code and the HTTP status code reason phrase OK. When the browser gets the response, it displays the body of the response and that’s why you see “Hello, World!” in your browser.”

web服务器的工作原理:

“The Web server creates a listening socket and starts accepting new connections in a loop. The client initiates a TCP connection and, after successfully establishing it, the client sends an HTTP request to the server and the server responds with an HTTP response that gets displayed to the user. To establish a TCP connection both clients and servers use sockets.”

你可能感兴趣的:(Python)