如何使用第一个可用端口在 Python 中创建 HTTP 服务器?
我想避免对端口号进行硬编码,如下所示:
httpd = make_server('', 8000, simple_app)
我以这种方式创建服务器的原因是我想将其用作 Adobe AIR 应用程序的“内核”,以便它将使用 PyAMF 进行通信。 由于我在客户端运行它,因此我定义的任何端口很可能已在使用中。 如果有更好的方法来做到这一点并且我问了错误的问题,请告诉我。
I want to avoid hardcoding the port number as in the following:
httpd = make_server('', 8000, simple_app)
The reason I'm creating the server this way is that I want to use it as a 'kernel' for an Adobe AIR app so it will communicate using PyAMF. Since I'm running this on the client side it is very possible that any port I define is already in use. If there is a better way to do this and I am asking the wrong question please let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是您需要一个已知的端口供应用程序使用。 但如果你给的端口号为0,我相信操作系统会为你提供第一个可用的未使用端口。
The problem is that you need a known port for the application to use. But if you give a port number of 0, I believe the OS will provide you with the first available unused port.
你是对的,先生。 其工作原理如下:
我现在有一个绑定到端口 54485 的套接字。
You are correct, sir. Here's how that works:
I now have a socket bound to port 54485.
make_server
是您编写的函数吗? 更具体地说,您是否处理创建套接字的代码? 如果这样做,应该有一种方法可以让您不指定端口号(或者指定 0 作为端口号),操作系统将为您选择一个可用的端口号。除此之外,您可以选择一个随机端口号,例如 54315...不太可能有人会使用该端口号。
Is
make_server
a function that you've written? More specifically, do you handle the code that creates the sockets? If you do, there should be a way where you don't specify a port number (or you specify 0 as a port number) and the OS will pick an available one for you.Besides that, you could just pick a random port number, like 54315... it's unlikely someone will be using that one.
防火墙允许您逐个端口允许或拒绝流量。 仅出于这个原因,没有明确定义端口的应用程序就应该在客户端安装中遇到各种问题。
我说选择一个随机端口,并让用户在需要时可以轻松更改端口。
这是知名端口的良好起点。
Firewalls allow you to permit or deny traffic on a port-by-port basis. For this reason alone, an application without a well-defined port should expect to run into all kinds of problems in a client installation.
I say pick a random port, and make it very easy for the user to change the port if need be.
Here's a good starting place for well-known ports.