简体   繁体   中英

MonoTorrent Event when piece written

I've been trying to use the C# MonoTorrent Library, but the lack of a documentation isn't helping. I'm trying to stream a file, but to do that, I somehow need an event whenever a Piece is written to file, or something similar.

I know there is an event which gets triggered whenever a Piece has been hashed, but it's not so useful when I need the actual content.

So I want to ask how I can know when a piece has been written to a file, so I can parse that and then stream that movie.

I already looked at the TorrentManager the ClientEngine the DiskManager and I haven't found anything useful in any of these classes nor any other Manager class. Now is this feature just hidden somewhere or do I have to do something different to get the pieces that were downloaded?

The PieceHashed event is what you need. When that event is raised you can be guaranteed that the data associated with that piece has been received, validated and written to the DiskManager.

If a MemoryWriter is being used that data may not be written to the underlying harddrive/SSD when the event is raised. To guarantee that you'll need to call the FlushAsync method, passing in the TorrentManager and piece index. If a piece is 256kB in size and there are three files of length 200kb, 50kb and 6kb contained within piece 6, all three of those files will be flushed if you pass in '6' as the piece index. If you call the overload which doesn't take a PieceIndex it will instead flush every file.

If you're writing something like a SlidingWindowPicker then you should probably only call FlushAsync when a piece in the high priority set has been downloaded. Any call to flush will flush all pending data for a given file (or all files). If the only data you have is from the very end of the torrent then flushing it immediately won't impact your ability to stream, but it may increase the overheads.

There is an alternative, which is to implement IPieceWriter and create a wrapper which flushes whenever an appropriate piece is written.

The existing MemoryWriter shows how to create a wrapper. It's Write method is implemented as follows: https://github.com/mono/monotorrent/blob/2209922c4159e394242c6c337401571312642b6e/src/MonoTorrent/MonoTorrent.Client.PieceWriters/MemoryWriter.cs#L118-L123 .

If you wanted to write something to automatically flush pieces you'd do something like:

public void Write(TorrentFile file, long offset, byte[] buffer, int bufferOffset, int count, bool forceWrite)
{
    Writer.Write(file, offset, buffer, bufferOffset, count);
    Writer.Flush(file);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM