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

本文介绍了一个简单的Python Web服务器实现过程,通过使用socket模块创建并监听一个HTTP服务。该服务器能够接收HTTP请求,并返回一个简单的'Hello, World!'响应。文章还解析了HTTP响应的基本结构及其在浏览器中的显示方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看完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/

得到结果为:
这里写图片描述

为什么代码明明是输出:

    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.”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值