我正在使用python创建一个Bittorrent客户端,并为流媒体文件进行扭曲,并且我已成功完成此操作。
我正在使用Twisted Framework连接到跟踪器和对等方。我可以从跟踪器中检索对等列表,并通过为每个对等体执行reactor.connectTCP()
函数来连接它们。
但我的客户端无法侦听TCP连接。意味着没有来自对等方的传入连接。我在给定端口使用reactor.listenTCP()
。我在请求数据包中使用的相同端口,我发送给跟踪器的通知请求。
我发送给跟踪器的请求数据包生成如下:
def udp_create_announce_request(connection_id, payload, s_port):
action = 0x1 #action (1 = announce)
transaction_id = udp_get_transaction_id()
buf = struct.pack("!q", connection_id) #first 8 bytes is connection id
buf += struct.pack("!i", action) #next 4 bytes is action
buf += struct.pack("!i", transaction_id) #followed by 4 byte transaction id
buf += struct.pack("!20s", urllib.unquote(payload['info_hash'])) #the info hash of the torrent we announce ourselves in
buf += struct.pack("!20s", urllib.unquote(payload['peer_id'])) #the peer_id we announce
buf += struct.pack("!q", int(urllib.unquote(payload['downloaded']))) #number of bytes downloaded
buf += struct.pack("!q", int(urllib.unquote(payload['left']))) #number of bytes left
buf += struct.pack("!q", int(urllib.unquote(payload['uploaded']))) #number of bytes uploaded
buf += struct.pack("!i", 0x2) #event 2 denotes start of downloading
buf += struct.pack("!i", 0x0) #IP address set to 0. Response received to the sender of this packet. IP decided by tracker.
key = udp_get_transaction_id() #Unique key randomized by client
buf += struct.pack("!i", key)
buf += struct.pack("!i", -1) #Number of peers required. Set to -1 for default
buf += struct.pack("!i", int(urllib.unquote(payload['port']))) #port on which response will be sent
return (buf, transaction_id)
创建数据包时是否有错误?或者没有同行试图连接到我的cliet的端口有不同的原因? Twisted中的Factory和Protocol实现是否存在问题?
反应堆调用的顺序如下:
factory = protocol.ServerFactory()
factory.protocol = Echo
self.reactor.listenTCP(self.port, factory)
for peer in peers:
self.reactor.connectTCP(peer.ip, peer.port, peerProtocol, timeout=10) # Working Properly
reactor.run()
Echo协议定义为:
class Echo(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Hello", data
# Never Printed
另外$ netstat -na | grep '{PORT}'
其中PORT是侦听端口,显示正确的端口设置以侦听