You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中PJSIP重启PC后报Address already in use问题求助

Properly Clean Up PJSIP Transport to Avoid "Address Already in Use" Error

The root of your problem is that setting transport = None only removes the Python reference to the transport object—it doesn’t tell the underlying PJSIP library to release the network resources tied to port 5060. When your program exits uncleanly (like when you restart the computer mid-execution), the port gets stuck in an occupied state, leading to the "Address already in use" error on your next run.

Here’s how to fix it properly:

  • Explicitly destroy the transport object
    Before discarding the transport reference, call its destroy() method to tell PJSIP to release the UDP port and associated resources:

    # When ending the call or shutting down
    if transport is not None:
        transport.destroy()
        transport = None
    
  • Properly shut down the PJSIP library instance
    Don’t forget to clean up the main lib object too, as it might hold onto other resources that could cause issues:

    lib.destroy()
    lib = None
    
  • Wrap cleanup in a try/finally block
    To ensure cleanup runs even if an error occurs during execution (which is common in telephony code), structure your main logic like this:

    def main():
        lib = None
        transport = None
        try:
            # Initialize PJSIP library
            lib = pj.Lib()
            lib.init()
            
            # Configure and create transport
            trans_cfg = pj.TransportConfig()
            trans_cfg.port = 5060
            trans_cfg.bound_addr = inputs.client_addr
            transport = lib.create_transport(pj.TransportType.UDP, trans_cfg)
            
            # ... Your call handling logic here ...
            
        finally:
            # Clean up resources no matter what
            if transport is not None:
                transport.destroy()
            if lib is not None:
                lib.destroy()
    

Your current workaround with lsof and kill works because it forces the stale process holding port 5060 to exit, but this is a manual band-aid. Implementing explicit cleanup in your code will prevent this issue from happening entirely, so you won’t need to run those commands after restarting your computer.

内容的提问来源于stack exchange,提问作者Raady

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:16:25