Python httpd 将监听已使用的端口,而不会在 Windows 中抛出套接字错误,但在 OS X 中不会?

标签 python cross-platform google-api oauth-2.0 apache

这实际上是我的 post 的后续内容。关于 Python oauth2 BaseHTTPServer 与 SABNzbd+ 冲突。

基本上,我有以下小脚本(用于创建监听 Google API oauth2 凭据的本地服务器):

import socket
import BaseHTTPServer
from oauth2client.tools import ClientRedirectServer, ClientRedirectHandler

port_number = 0
host_name = 'localhost'
for port_number in range(8080,10000):
    try:
        httpd = ClientRedirectServer((host_name, port_number),
                                   ClientRedirectHandler)
    except socket.error, e:
        print "socket error: " + str(e)
        pass
    else:
        print "The server is running on: port " + str(port_number)
        print "and host_name " + host_name
        httpd.serve_forever()
        break

在 OS X 上,如果我运行此脚本两次,我会得到预期的结果:

socket error: [Errno 48] Address already in use
The server is running on: port 8081
and host_name localhost

但是,在 Win7 中从不同的 cmd 窗口运行相同的脚本,我可以愉快地在同一端口 (8080) 上运行 3 或 4 个服务器,而不会引发套接字错误:

C:\>netstat -abn | Findstr 8080
TCP    127.0.0.1:8080    0.0.0.0:0    LISTENING
TCP    127.0.0.1:8080    0.0.0.0:0    LISTENING

最佳答案

显然,对于将多个套接字绑定(bind)到同一地址/端口,Windows 与大多数 Unix-y 系统具有不同的语义。例如,参见 this Python issue其中。

关于Python httpd 将监听已使用的端口,而不会在 Windows 中抛出套接字错误,但在 OS X 中不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8772444/

相关文章:

python - 多条件 np.extract

sockets - 有没有开源的跨平台NAT穿通?

c# - 使用 Google Drive API v3 移动文件

javascript - 如何创建动态HTTP请求路径

python - 读取文件名并直接写入列表

python - 如何将下面的代码转换为python代码,它是为了校验和。请有人能给我一些指导来学习一些东西来实现这一目标

c++ - CMake:覆盖由 target_link_libraries 添加的库

html - 如何对 DOC/DOCX 转换为 HTML 进行后期格式化?

python - 尝试将python的Google视觉响应转换为字典时出现属性错误DESCRIPTOR

python - 为什么比较返回一个整数而不是 bool 值?