python - TCPServer 与 HTTPServer

标签 python httpserver tcpserver

我正在编写一个简单的 python3 网络服务器。我已经尝试了各种教程,并且都运行良好。尽管如此,还是有一点我不明白。

在一个教程中,他们使用 HTTPServer 如下:

server = HTTPServer(('', PORT_NUMBER), myHandler) 
server.serve_forever()

在另一个教程中,他们使用 socketserver.TCPServer 如下:

with socketserver.TCPServer(('', PORT_NUMBER), myHandler) as httpd:
    httpd.serve_forever()

这两种方法有什么区别?我所需要的只是一个简单的网络服务器,它能够通过 POST 接收 JSON 文件并用另一个 JSON 进行回答。在这两种情况下,我都会使用相同的处理程序:

class myHandler(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write("{dummy:'dummy'}")

    def do_POST(self):
        # Doesn't do anything with posted data for this example
        self._set_headers()
        self.wfile.write("{dummy:'dummy'}")

其中一种方法是否更适合我的需要?有没有更好的方法来编写这个服务器来满足我的需要?

感谢您的帮助和时间!

最佳答案

TCP 是OSI 第 4 层传输协议(protocol),而 HTTP 是更高层的第 7 层应用协议(protocol),建立在 TCP 之上。

事实上,根据documentation,看起来HTTPServer 直接继承自socketserver.TCPServer。 :

One class, HTTPServer, is a socketserver.TCPServer subclass. It creates and listens at the HTTP socket, dispatching the requests to a handler.

例如,TCP 将负责建立连接(使用SYNSYN-ACKACK 的三向握手)但它在数据交互(请求/响应)的结构方面并没有真正规定太多。如果您使用 TCP 协议(protocol),您通常需要自己编写所有数据处理代码。

All I need is a simple webserver that is able to receive JSON files through POSTs and aswer with another JSON

这表明 HTTP 服务器更适合您的需求,因为 POST 的概念以及您对 answer with another JSON 的描述可能会包括响应(带有响应主体、响应 header 和响应状态)。所有这些都将是 HTTP 概念。作为 http.server 的文档。 BaseHTTPRequestHandler 声明,它将包含一个名为 command 的实例变量,它是您的请求方法(例如 GET)。

我无法确切地说出您的示例代码中是如何分配 myhandler 的,但是查看其他一些文档示例,它看起来像一个 http.server.SimpleHTTPRequestHandler:

import http.server
import socketserver

PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

服务器实例化工作的常见模式似乎是

  1. 实例化一个较低级别的协议(protocol)服务器(即 TCP)并传入一个较高级别的处理程序(如 http.server.SimpleHTTPRequestHandler),因此 socketserver.TCPServer(("", PORT), myhandler).
  2. 在上下文管理器中使用它(with 关键字),很可能是因为您需要在服务器完成执行后拆除/释放资源。

关于python - TCPServer 与 HTTPServer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58045415/

相关文章:

javascript - 从 npm 脚本在后台运行 http-server

iphone - Apple IOS 应用程序和 Delphi TidCmdTcpServer

php - 使用 xampp 和 phpmailer 的奇怪错误

c++ - 在游戏机上加载的最佳数据文件格式

python - 是否自导入分包?

python - 分解多个 pandas 列并取消嵌套一列作为列名

python - 设置监听文件套接字的 HTTP 服务器

go - TCP监听器没有完全关闭

c - 收割者调用后服务器堵塞

python - 更多相对进口奇数 : . 。符号