【问题标题】:python websockets set port as None, how can get which port used?python websockets设置端口为无,如何获取使用的端口?
【发布时间】:2021-07-12 09:09:26
【问题描述】:

我使用python websockets库创建了一个websocket服务器,为了避免端口被其他应用程序使用,我将端口设置为无,让系统为我的websocket服务器选择一个端口。我的问题是如何从程序中获取我的 websocket 服务器使用的端口?

【问题讨论】:

  • 当您尝试阅读文档时发生了什么?

标签: python websocket python-asyncio


【解决方案1】:

但是,我没有找到如何使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2017-07-08
    • 1970-01-01
    • 2017-05-27
    • 2013-10-27
    • 2016-04-19
    • 1970-01-01
    相关资源
    最近更新 更多