/// <summary> /// Process any piece requests in buffer and send to remote peer. /// </summary> /// <param name="cancelTask"></param> /// <returns></returns> private void PieceRequestProcessing(CancellationToken cancelTask) { try { Log.Logger.Info("Piece request processing task started..."); while (true) { Peer remotePeer = null; PieceRequest request = pieceRequestQueue.Take(cancelTask); try { Log.Logger.Info($"Piece Reqeuest {request.pieceNumber} {request.blockOffset} {request.blockSize}."); if (_manager.GetPeer(request.infoHash, request.ip, out remotePeer)) { PieceBuffer requestBuffer = GetPieceFromTorrent(remotePeer, request.pieceNumber); byte[] requestBlock = new byte[request.blockSize]; Array.Copy(requestBuffer.Buffer, (Int32)request.blockOffset, requestBlock, 0, (Int32)request.blockSize); PWP.Piece(remotePeer, request.pieceNumber, request.blockOffset, requestBlock); remotePeer.Tc.TotalBytesUploaded += request.blockSize; } } catch (Exception ex) { Log.Logger.Error(ex); // Remote peer most probably closed socket so close connection remotePeer?.Close(); } } } catch (Exception ex) { Log.Logger.Debug(ex); } Log.Logger.Info("Piece request processing task terminated."); }
/// <summary> /// Handles request command from remote peer. /// </summary> /// <param name="remotePeer">Remote peer.</param> private static void HandleREQUEST(Peer remotePeer) { PieceRequest request = new PieceRequest { infoHash = remotePeer.Tc.infoHash, ip = remotePeer.Ip, pieceNumber = Util.UnPackUInt32(remotePeer.ReadBuffer, 1), blockOffset = Util.UnPackUInt32(remotePeer.ReadBuffer, 5), blockSize = Util.UnPackUInt32(remotePeer.ReadBuffer, 9) }; remotePeer.Tc.pieceRequestQueue.Add(request); Log.Logger.Info($"{RemotePeerID(remotePeer)}RX REQUEST {request.pieceNumber} Block Offset {request.blockOffset} Data Size {request.blockSize}."); }