gpt4 book ai didi

Python无法制作网络服务器

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:52 24 4
gpt4 key购买 nike

我正在尝试使用 Socket 模块制作一个 python 网络服务器。我正在关注这个视频 https://www.youtube.com/watch?v=_najJkyK46g .

这是我的代码:

import socket

host = ''
port = 8000

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("Listening on port "+str(port))

while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024)
print(request)

http_response = "Hello World."

client_connection.sendall(bytes(http_response.encode('utf-8')))
client_connection.close()

当我转到 chrome 并输入 127.0.0.1:8000 时,它不起作用。它提出了一个错误,说“这个页面不工作”。 127.0.0.1 发送了无效响应。 ERR_INVALID_HTTP_RESPONSE。请帮帮我好吗?

最佳答案

Chrome 期待一个结构化协议(protocol)的 HTTP 响应,Hello World. 不符合:

https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Response_message

The response message consists of the following:

A status line which includes the status code and reason message (e.g., HTTP/1.1 200 OK, which indicates that the client's request succeeded). Response header fields (e.g., Content-Type: text/html). An empty line. An optional message body. The status line and other header fields must all end with . The empty line must consist of only and no other whitespace.[31] This strict requirement for is relaxed somewhat within message bodies for consistent use of other system linebreaks such as or alone.[33]

更新到以下响应应该有效:

HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Encoding: UTF-8
Content-Length: 138
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
ETag: "3f80f-1b6-3e1cb03b"
Accept-Ranges: bytes
Connection: close

<html>
<head>
<title>An Example Page</title>
</head>
<body>
Hello World, this is a very simple HTML document.
</body>
</html>

如果您打算让服务器通过 HTTP 进行通信,我绝对会推荐一个 python Web http 框架,其中有很多。两个非常轻的是:

关于Python无法制作网络服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47784859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com