Пример #1
0
 def __handlepeer( self, clientsock ):
 
 	"""
 	handlepeer( new socket connection ) -> ()
 
 	Dispatches messages from the socket connection
 	"""
 
 	self.__debug( 'New child ' + str(threading.currentThread().getName()) )
 	self.__debug( 'Connected ' + str(clientsock.getpeername()) )
 
 	host, port = clientsock.getpeername()
 	peerconn = PeerConnection( None, host, port, clientsock )
 	
 	try:
 	    msgtype, msgdata = peerconn.recvdata()
 	    if msgtype: 
             msgtype = msgtype.upper()
 	    if msgtype not in self.handlers:
             self.__debug( 'Not handled: %s: %s' % (msgtype, msgdata) )
 	    else:
             self.__debug( 'Handling peer msg: %s: %s' % (msgtype, msgdata) )
 		self.handlers[ msgtype ]( peerconn, msgdata )
 	except KeyboardInterrupt:
 	    raise
 	except:
 	    if self.debug:
 		traceback.print_exc()
 	
 	self.__debug( 'Disconnecting ' + str(clientsock.getpeername()) )
 	peerconn.close()
Пример #2
0
 def checklivepeers( self ):
 
 	""" Attempts to ping all currently known peers in order to ensure that
 	they are still active. Removes any from the peer list that do
 	not reply. This function can be used as a simple stabilizer.
 
 	"""
 	todelete = []
 	for pid in self.peers:
 	    isconnected = False
 	    try:
     		self.__debug( 'Check live %s' % pid )
     		host,port = self.peers[pid]
     		peerconn = PeerConnection( pid, host, port)
     		peerconn.senddata( 'PING', '' )
     		isconnected = True
 	    except:
             todelete.append( pid )
 	    if isconnected:
             peerconn.close()
 
 	self.peerlock.acquire()
 	try:
 	    for pid in todelete: 
             if pid in self.peers:
                 del self.peers[pid]
 	finally:
 	    self.peerlock.release()
Пример #3
0
    def _handle_peer(self, client_socket):
        """ Method looks for the appropriate handler for a message, dispatches the request to an appropriate handler (function or method) for processing. """
        print('Connected ' + str(client_socket.getpeername()))
        host, port = client_socket.getpeername()
        peer_connection = PeerConnection(host=host,
                                         port=port,
                                         socket=client_socket,
                                         peer_id=None,
                                         debug=False)

        try:
            # to implement
            msg_data = peer_connection.recv_data()
            print("Message data primljen: ", msg_data)
            #if msg_type:
            #    msg_type = msg_type.lower()

            # self.handlers are message type handlers, hash table with function pointer
            #if msg_type not in self.handlers:
            #    self.__debug( 'Handling peer msg: %s: %s' % (msg_type, msg_data) )
            #    self.handlers[ msg_type ]( peer_connection, msg_data )
        except KeyboardInterrupt:
            pass
        print('Disconnecting ' + str(client_socket.getpeername()))
        peer_connection.close()
Пример #4
0
    def connect(self):
        # print self.peer_list

        connected_peers = []
        for peer in self.peer_list:
            peer_connection = PeerConnection(self.peer_id,
                                             peer,
                                             self.info_hash)

            if peer_connection.is_connected():
                connected_peers.append(peer_connection)
                peer_connection.run()

        logging.debug("{} peer(s) connected for".format(len(connected_peers)))

        return connected_peers
Пример #5
0
    def connectandsend( self, host, port, msgtype, msgdata, 
			pid=None, waitreply=True ):
   
    	"""
    	connectandsend( host, port, message type, message data, peer id,
    	wait for a reply ) -> [ ( reply type, reply data ), ... ]
    
    	Connects and sends a message to the specified host:port. The host's
    	reply, if expected, will be returned as a list of tuples.
    
    	"""
        
    	msgreply = []
    	try:
            
    	    peerconn = PeerConnection( pid, host, port )
            
    	    peerconn.sendData( msgtype, msgdata )
    	
    	    
    	    if waitreply:
        		onereply = peerconn.recvData()
        		while (onereply != (None,None)):
        		    msgreply.append( onereply )
        		    print ( 'Got reply %s: %s' 
        				  % ( pid, str(msgreply) ) )
        		    onereply = peerconn.recvData()
    	    peerconn.close()
    	except KeyboardInterrupt:
    	    raise
    	except:
    	    if False:
    		      traceback.print_exc()
    	
    	return msgreply
Пример #6
0
    def connectAndSend( self, host, port, msgType, msgData, 
			pid=None, waitreply=True ):
   
    	msgreply = []
        num = self.getAttemptedConnectionNumber()
        
        while  num != Peer.NUMBER:
            
            print "ConnectAndSend peers from (%s,%s) %s number %d" % (host,port,msgType,num)
            try:
                peerConn = PeerConnection( pid, host, port)
                peerConn.sendData( msgType, msgData )
                if waitreply:
                    onereply = peerConn.recvData()
                    while (onereply != (None,None)):
                        msgreply.append( onereply )
                        print 'Got reply %s: %s' % ( pid, str(msgreply) )
                        onereply = peerConn.recvData()
                peerConn.close()
                break
            except KeyboardInterrupt:
                raise
            except:
                num += 1
                print "Erro de Connecao peers from (%s,%s) %s %d" % (host,port,msgType, num)
        
        if num == Peer.NUMBER:
            self.setMySuperPeer(self.getMyID())
            self.setPeerType(Peer.SUPER)
            
    	return msgreply
Пример #7
0
    def check_live_peers(self):
        """ Attempts to ping all known peers to ensure that they are still active. If they are not active remove from list --> Simple stabilizer. """
        to_delete = []
        # loop over peers and send msg PING
        for p_id in self.peers:
            is_active = False
            try:
                print('Check live %s' % p_id)
                host, port = self.peers[p_id]
                peer_connection = PeerConnection(p_id,
                                                 host,
                                                 port,
                                                 debug=self.debug)
                peer_connection.senddata('PING', '')
                is_active = True
            except:
                to_delete.append(p_id)

            if is_active:
                peer_connection.close()
        # acquire lock to delete non active peers
        self.peer_lock.acquire()
        try:
            for p_id in to_delete:
                if p_id in self.peers:
                    del self.peers[p_id]
        except:
            pass