【问题标题】:Socket disconnected after a message, (Connection refused by remote host), using python消息后套接字断开连接,(远程主机拒绝连接),使用python
【发布时间】:2025-12-19 00:55:01
【问题描述】:

我已经在 azure 上上传了我的 python 套接字(云服务项目),并且当我连接到 Hercules 客户端套接字时......在一两条消息之后,远程主机关闭了连接......强行...... .?

服务器代码

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
import SocketServer
class IphoneChat(Protocol):
    def connectionMade(self):
        self.factory.clients.append(self)
        print('clients are'), self.factory.clients                  
    def connectionLost(self, reason):
        self.factory.clients.remove(self)        
    def dataReceived(self, data):
        msg = ""
        msg =  data.strip()
        for c in self.factory.clients:
            c.message(msg)                  
    def message(self, message):
        self.transport.write(message + '\n')        

print ('Iphone Chat server startedd')
factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(9073, factory)
reactor.run()

【问题讨论】:

  • 项目是作为辅助角色运行还是仅在 Azure VM 实例上运行?
  • 是的,作为工人角色....?
  • 在我的解决方案中,我有两个项目,一个是工作角色,第二个是 python 云服务,工作角色在发布到 azure 之前作为 statup 项目......
  • 这个项目是什么?

标签: python sockets azure


【解决方案1】:

我尝试在我的环境中重现您的问题,但失败了。根据我的经验,如果我们在 azure worker 角色中使用套接字,我们通常会注意 3 点。

  1. 打开输入 TCP 端口。如果我们打开一个端口作为监听端口,我们最好将此端口添加到端点设置中。

  2. 考虑到worker角色状态,我建议我们可以将逻辑编码到while True循环函数中,如下,

    while True:
        reactor.listenTCP(65534, f)
        print "server run"
        reactor.run()
        sleep(1.0)
    
  3. 根据报错信息,我猜原因是天蓝色负载均衡器会在240s内杀死空闲连接。我建议你可以参考这个blog 来配置你的idleTimeoutInMinutes 值。

请尝试检查您的项目和配置。任何进一步的发现,请告诉我。

【讨论】:

  • 我按照你说的重置了上面的配置,但是现在我无法连接到 23.96.57.211:9073 的套接字虚拟 IP? TCP 连接超时
  • 在你上面提到的BLOG上,默认空闲时间是4分钟....但问题是我的连接在几秒钟内丢失了......?
  • 我会深入研究它。感谢您的耐心等待。
  • @salmanrafiq,对于这个问题的延误,我们深表歉意,感谢您的耐心等待。我的同事和我无法重现此问题,您能否打开服务请求并直接与支持团队合作?
  • 什么支持团队?以及如何?