public void tick() { peersManager.tick(); choker.tick(); Long waitTime = activeTracker.getInterval(); if (incomingPeerListener.getReceivedConnection() == 0 || peersManager.getActivePeersNumber() < 4) { waitTime = activeTracker.getMinInterval() != null ? activeTracker.getMinInterval() : 60; } long now = System.currentTimeMillis(); if (now - activeTracker.getLastRequestTime() >= waitTime * 1000) { if (!stopped) { try { Object peers = trackerRequest(null).get(ByteBuffer.wrap("peers".getBytes())); if (peers != null) { addPeers(peers); } } catch (Exception e) { e.printStackTrace(); } } } }
public void piece(int index, int begin, byte[] block, Peer peer) { try { torrentDisk.write(index, begin, block); pieceChooser.piece(index, begin, block, peer); } catch (Exception e) { if (Torrent.verbose) { addEvent(new Event(e, "Exception writing piece", Level.SEVERE)); } e.printStackTrace(System.err); } if (Torrent.verbose) { addEvent( new Event( peer, "PIECE " + index + " " + ((float) torrentDisk.getDownloaded(index) / torrentDisk.getLength(index)), Level.FINEST)); } if (torrentDisk.isCompleted(index)) { peersManager.sendHave(new Have(index)); } addRequests(peer); }
private void addRequests(Peer peer) { Request request = null; int[] piecesFrequencies = peersManager.getPiecesFrequencies(); while (peer.getUnfulfilledRequestNumber() < maxUnfulfilledRequestNumber && (request = pieceChooser.getNextBlockRequest(peer, piecesFrequencies)) != null) { peer.sendMessage(request); } if (request == null && peer.getUnfulfilledRequestNumber() == 0) { peer.setAmInterested(false); } }
public void addPeers(Object peers) throws UnknownHostException { if (peers instanceof List) { List peersList = (List) peers; for (Object elem : peersList) { Map peerMap = (Map) elem; ByteBuffer addressByteBuffer = (ByteBuffer) peerMap.get(ByteBuffer.wrap("ip".getBytes())); InetAddress address = InetAddress.getByName(new String(addressByteBuffer.array())); int port = ((Long) peerMap.get(ByteBuffer.wrap("port".getBytes()))).intValue(); ByteBuffer peerIdByteByteBuffer = (ByteBuffer) peerMap.get(ByteBuffer.wrap("peer id".getBytes())); byte[] peerIdByteString = peerIdByteByteBuffer.array(); if (Torrent.verbose) { addEvent(new Event(this, "Offering new peer: " + address, Level.FINE)); } peersManager.offer(peerIdByteString, address, port); } } else if (peers instanceof ByteBuffer) { byte[] peersString = ((ByteBuffer) peers).array(); for (int i = 0; i < peersString.length / 6; i++) { byte[] peerByteAddress = new byte[4]; System.arraycopy(peersString, i * 6, peerByteAddress, 0, 4); InetAddress address = InetAddress.getByAddress(peerByteAddress); int port = ((peersString[i * 6 + 4] & 0xFF) << 8) | (peersString[i * 6 + 5] & 0xFF); if (Torrent.verbose) { addEvent(new Event(this, "Offering new peer: " + address, Level.FINE)); } peersManager.offer(null, address, port); } } else { System.err.println("WTF!!!"); } }