示例#1
0
文件: dht.py 项目: gofetch/fetchfs
class DHT:
    def __init__(self, bootstrap_node, local_ip='localhost', local_port=8000):
        self.selfnode = Peer(local_ip, local_port)
        self.server = StreamingServer(self._handle, local_ip, local_port)
        self.peers = PeerList()
        self.peers.add(self.selfnode)
        self.table = dict()
        self.server.start()
        if bootstrap_node:
            message(bootstrap_node, BOOTSTRAP,
                    {'ip': local_ip, 'port': local_port})
    
    def _handle(self, conn, data):
        resp = json.loads(data)
        
        if resp['msg'] == BOOTSTRAP:
            newpeer = Peer(resp['ip'], resp['port'])
            peertuples = [p.astuple() for p in self.peers]
            message(newpeer.astuple(), PEERS, {'peers': peertuples})
            self.peers.add(newpeer)
        
        elif resp['msg'] == PEERS:
            others = resp['peers']
            for ip, port in others:
                peer = Peer(ip, port)
                self.peers.add(peer)
                message(peer.astuple(), ANNOUNCE,
                        {'ip': self.selfnode.ip, 'port':self.selfnode.port})
        
        elif resp['msg'] == ANNOUNCE:
            peer_ip = resp['ip']
            peer_port = resp['port']
            self.peers.add(Peer(peer_ip, peer_port))
        
        elif resp['msg'] == SET:
           key, value = hash(resp['key']), resp['value']
           self.table[key] = value
        
        elif resp['msg'] == GET:
            key = hash(resp['key'])
            if self.table.has_key(key):
                message(conn, RECV, {'value': self.table[key]})
            else:
                message(conn, RECV, {'value': None})
    
    def __getitem__(self, key):
        for p in self.peers.list:
            resp = message(p.astuple(), GET, {'key':key}, receive=True)
            if resp and resp['value']:
                return resp['value']
    
    def __setitem__(self, key, value):
        peer = random.choice(self.peers.list)
        message(peer.astuple(), SET, {'key': key, 'value':value})
    
    def update(self, d):
        for k in d:
            self[k] = d[k]
示例#2
0
文件: dht.py 项目: gofetch/fetchfs
 def __init__(self, bootstrap_node, local_ip='localhost', local_port=8000):
     self.selfnode = Peer(local_ip, local_port)
     self.server = StreamingServer(self._handle, local_ip, local_port)
     self.peers = PeerList()
     self.peers.add(self.selfnode)
     self.table = dict()
     self.server.start()
     if bootstrap_node:
         message(bootstrap_node, BOOTSTRAP,
                 {'ip': local_ip, 'port': local_port})