【发布时间】:2021-07-12 09:09:26
【问题描述】:
我使用python websockets库创建了一个websocket服务器,为了避免端口被其他应用程序使用,我将端口设置为无,让系统为我的websocket服务器选择一个端口。我的问题是如何从程序中获取我的 websocket 服务器使用的端口?
【问题讨论】:
-
当您尝试阅读文档时发生了什么?
标签: python websocket python-asyncio
我使用python websockets库创建了一个websocket服务器,为了避免端口被其他应用程序使用,我将端口设置为无,让系统为我的websocket服务器选择一个端口。我的问题是如何从程序中获取我的 websocket 服务器使用的端口?
【问题讨论】:
标签: python websocket python-asyncio
但是,我没有找到如何使用 websockets 或 asyncio 来获取端口。我使用 netstat -ano 来获取端口。这是我的代码:
def get_server_port():
try:
current_pid = os.getpid()
log_utils.get_logger().info(current_pid)
netstat_cmd = "netstat -ano"
outs, errs = windows_utils.run_cmd(netstat_cmd, encoding='GBK')
if errs:
log_utils.get_logger().error(errs)
else:
lines = outs.split('\r\n')
for line in lines:
temp = [i for i in line.split(' ') if i != '']
if len(temp) > 4:
if temp[4] == str(current_pid) and temp[3] == 'LISTENING':
print(temp)
address_array = temp[1].split(':')
if len(address_array) > 1:
port_str = address_array[1]
return int(port_str)
except BaseException as e:
log_utils.get_logger().exception(e)
【讨论】: