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

如何将Twisted Python代码部署至公网?修改代码实现监听指定域名而非localhost

解决方案:让Twisted回显服务器支持公网访问

首先要明确一个关键点:服务器程序不需要直接监听域名,域名只是用来解析到服务器的公网IP地址。我们只需要让服务器监听服务器上的所有可用网络接口(或者指定公网IP),再配合域名解析和防火墙配置,就能实现通过域名访问。

步骤1:修改代码监听所有接口

你的现有代码中,TCP4ServerEndpoint默认会监听0.0.0.0(所有网络接口),但为了明确起见,我们可以显式指定这个参数,避免歧义:

from twisted.internet.protocol import Protocol , Factory
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ServerEndpoint

connections = -1

class echo_simple(Protocol):
    def connectionMade(self):
        global connections
        connections += 1
        self.transport.write(f'Number of active connections in the server are: {connections} '.encode('utf-8'))
    def connectionLost(self,*args , **kwargs):
        global connections
        connections -= 1
        print(':: N :: A Connection Just Closed :: N ::')
    def dataReceived(self, data):
        data = data.decode('utf-8')
        print(f':C: {data} ')
        self.transport.write("\n Server Successfully Received Your Message!".encode('utf-8'))
        self.transport.write(f"\n |THE MESSAGE YOU SENT IS : {data}|".encode('utf-8'))
        self.transport.write(f'\n Closing The Connection As This is Just An Echo Server'.encode('utf-8'))
        self.transport.loseConnection()

class Server_factory(Factory):
    def buildProtocol(self, addr):
        print(" |^INFO^| Created An Instance ")
        return echo_simple()

# 显式指定监听所有接口(0.0.0.0)和端口8009
endpoint = TCP4ServerEndpoint(reactor, 8009, interface="0.0.0.0")
endpoint.listen(Server_factory())
reactor.run()

这里的interface="0.0.0.0"表示服务器会监听服务器上的所有网络接口,包括公网IP、内网IP和本地回环地址。

步骤2:配置域名解析

登录你的域名管理后台(比如域名服务商的控制台),添加一条A记录,将www.examplecode.com指向你的服务器的公网IP地址。

等待域名解析生效(通常需要几分钟到几小时,视TTL设置而定)。

步骤3:开放服务器防火墙端口

确保你的服务器防火墙(比如iptables、ufw、阿里云安全组等)已经开放了8009端口,允许外部网络的TCP流量访问这个端口。

举几个常见的操作例子:

  • 如果你用ufw(Ubuntu/Debian):
    sudo ufw allow 8009/tcp
    sudo ufw reload
    
  • 如果你用iptables:
    sudo iptables -A INPUT -p tcp --dport 8009 -j ACCEPT
    sudo service iptables save
    
  • 云服务器用户:需要在云服务商的安全组规则中添加允许8009端口的入站规则。

验证访问

完成以上步骤后,你就可以通过www.examplecode.com:8009来访问你的回显服务器了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 20:07:34