我正在使用Twisted在Python中创建点对点应用程序。它在我的VPS之间工作得很好但是当我尝试连接到我的家用机器时它不起作用。我认为它与我的路由器上的NAT或防火墙有关。我的问题是,有没有人知道如何绕过路由器防火墙或连接到使用Twisted的NAT后面的机器?这是我的代码:
from twisted.internet import reactor, protocol
from twisted.protocols import basic
from sys import *
import os.path
if (argv[1] == ""):
HOST = "localhost"
else:
HOST = argv[1]
PORT = 9001
if (os.path.isfile("zones/root.txt")):
root = open("zones/root.txt", "rw").read()
else:
root = ""
root1 = root
root2 = ""
maxPeers = 8
peerCount = 0
routingTable = []
ipaddress = []
depth = 0
ip = ""
peerId = ""
class p2pClient(basic.LineReceiver):
global root
global root2
global checkRoot
global depth
clientTable = []
def checkRoot(root2):
if (root1 == root2):
print "Roots are the same"
else:
print "Different roots."
def connectionMade(self):
print "connected to peer!"
def connectionLost(self, reason):
print "Disconnected from server!"
def lineReceived(self, data):
data = data.split("{}")
clientTable = data[0].replace("[","").replace("]","").replace("'","").replace(" ","").split(",")
root2 = data[1]
checkRoot(root2)
class p2pClientFactory(protocol.ClientFactory):
protocol = p2pClient
class p2pServer(basic.LineReceiver):
global routingTable
global addToRoutingTable
global removeFromRoutingTable
global ipaddress
def replace(l, X, Y):
for i,v in enumerate(l):
if v == X:
l.pop(i)
l.insert(i, Y)
def removeFromRoutingTable(ip):
routingTable.remove(ip)
def addToRoutingTable(ip):
routingTable.append(ip)
def sendData(self, msg):
self.transport.write("%s\r\n" % msg)
def connectionMade(self):
global peerCount # global allows us to use peerCount in our class
global depth
peerCount = peerCount + 1 # Update the peer count
#ip = self.transport.getHost().host
ip = self.transport.getPeer()
ip = str(ip)
ip = ip.split("'")
ip = ip[1]
ipaddress.append(ip)
addToRoutingTable(ip)
self.transport.write(str(routingTable) + "{}")
self.sendData(root) # Send the root zone file to peer 1
print "Peer Count : [ " + str(peerCount) + " / 8 ]"
print "Routing Table: " + str(routingTable)
def connectionLost(self, reason):
global peerCount
peerCount = peerCount - 1
ipaddr = str(self.transport.getPeer()).split("'")
removeFromRoutingTable(ipaddr[1])
print "Client Disconnected!"
print "Peer Count : [ " + str(peerCount) + " / 8 ]"
print "Routing Table : " + str(routingTable)
class p2pServerFactory(protocol.Factory):
protocol = p2pServer
sfactory = p2pServerFactory()
reactor.listenTCP(PORT, sfactory)
cfactory = p2pClientFactory()
reactor.connectTCP(HOST, PORT, cfactory)
reactor.run()
我很欣赏代码很长,但我非常感谢任何帮助。谢谢!
答案 0 :(得分:1)
你编码和你使用扭曲的事实在这里是无关紧要的。您必须在路由器中设置NAT以将端口9001转发到本地计算机的IP。进行配置的方法是路由器依赖。搜索" NAT端口转发+ routername"。我认为这是一个很好的起点。 可能在极少数情况下是防火墙问题,但它更像是一个NAT问题。
答案 1 :(得分:1)
如果要使用Twisted编写对等应用程序,Vertex提供了一些NAT遍历逻辑的实现,用于通过UDP建立基于流的连接。不幸的是,它的文档相当薄,准确地写出如何使用它对于SO答案来说是相当冗长的,但如果你尝试使用它并开始提交错误,你可能会激发项目的一些活动:-)。