简体   繁体   English

为什么 Python 会锁定端口? 这可以安全地用于简单的概念验证实时应用吗

[英]Why does Python lock the port? And can this be safely used for simple proof of concept live app

This is interesting.这是有趣的。 I did a simple script to bind and serve http but I hadn't done this in Python3.我做了一个简单的脚本来绑定和服务http但我没有在 Python3 中这样做。 I can write a simple server:我可以写一个简单的服务器:

import http.server
import socketserver

PORT = 8002

Handler = http.server.SimpleHTTPRequestHandler
#https://docs.python.org/3/library/http.server.html
class MyHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, request, client_addr, server):
        super().__init__(request, client_addr, server)
    def do_GET(self, ):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.wfile.write('Hey!'.encode())

httpd = socketserver.TCPServer(("0.0.0.0", PORT), MyHandler)

print("serving at port", PORT)
httpd.serve_forever()

but when I run it, then Ctrl+c, then run it again it says:但是当我运行它时,然后 Ctrl+c,然后再次运行它,它说:

OSError: [Errno 98] Address already in use OSError: [Errno 98] 地址已在使用中

Why is that if I kill the previous process?如果我杀死前一个进程,为什么会这样?

Also, is there any reason other than that that this couldn't be used as a simple, testing webapp for a test server at IP :port/somesamplewebapp - They say "http.server is not recommended for production. It only implements basic security checks."此外,除了不能将其用作IP 的测试服务器的简单测试 webapp 之外,是否还有其他原因:port/somesamplewebapp - 他们说“不建议将 http.server 用于生产。它仅实现基本安全性检查。” but if it does not need https or extra security... what are the risks?但如果它不需要 https 或额外的安全性......有什么风险?

The operating system prevents, by default, the reuse of an address by a different PID.默认情况下,操作系统会阻止不同 PID 重用地址。 You can defeat that with the socket option SO_REUSEADDR .您可以使用套接字选项SO_REUSEADDR来解决这个问题。 However, since you are using the TCPServer class and it has it's own, different, way of specifying that.但是,由于您使用的是 TCPServer class 并且它有自己的不同的指定方式。 You can use this code.您可以使用此代码。


import http.server
import socketserver

PORT = 8002

Handler = http.server.SimpleHTTPRequestHandler

#https://docs.python.org/3/library/http.server.html

class MyHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, request, client_addr, server):
        super().__init__(request, client_addr, server)

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.wfile.write('Hey!'.encode())


class MyServer(socketserver.TCPServer):
    allow_reuse_address = True  # <-- This is what you need


httpd = MyServer(("0.0.0.0", PORT), MyHandler)

print("serving at port", PORT)

httpd.serve_forever()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM