Skip to content

Commit

Permalink
switched to 2.0 for use in more frameworks, and some tidying up
Browse files Browse the repository at this point in the history
  • Loading branch information
bizzehdee committed Oct 4, 2023
1 parent 3224320 commit c232625
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 36 deletions.
13 changes: 7 additions & 6 deletions Demo/Program.cs
Expand Up @@ -19,7 +19,7 @@ class Program
static string inputFilename;
static string downloadDirectory;
static IMetadata downloadMetadata;
static List<IPEndPoint> knownPeers = new();
static readonly List<IPEndPoint> knownPeers = new();

static void Main(string[] args)
{
Expand Down Expand Up @@ -76,7 +76,7 @@ static void Main(string[] args)
trackerClient = new UDPTrackerClient(5);
}

var announceInfo = trackerClient.Announce(tracker, downloadMetadata.HashString, peerId, 0, downloadMetadata.PieceHashes.Count() * downloadMetadata.PieceSize, 0, 0, 0, 256, 12345, 0);
var announceInfo = trackerClient.Announce(tracker, downloadMetadata.HashString, peerId, 0, downloadMetadata.PieceHashes.Count * downloadMetadata.PieceSize, 0, 0, 0, 256, 12345, 0);
if (announceInfo == null)
{
Console.WriteLine("Error announcing to {0}", tracker);
Expand Down Expand Up @@ -120,15 +120,16 @@ static void Main(string[] args)
}
}

var socket = new PeerWireuTPConnection();
socket.Timeout = 5;
var socket = new PeerWireuTPConnection
{
Timeout = 5
};

var client = new PeerWireClient(socket)
{
KeepConnectionAlive = true
};

//var peer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6881); //rappid testing against local install of qBittorrent

foreach (var peer in knownPeers)
{
try
Expand Down
7 changes: 4 additions & 3 deletions bzTorrent/IO/PeerWireTCPConnection.cs
Expand Up @@ -135,8 +135,9 @@ public bool Process()
socket.BeginReceive(socketBuffer, 0, socketBufferSize, SocketFlags.None, ReceiveCallback, this);
}

while (sendQueue.TryDequeue(out var packet))
while(sendQueue.Count > 0)
{
var packet = sendQueue.Dequeue();
socket.Send(packet.GetBytes());
}

Expand All @@ -150,9 +151,9 @@ public void Send(PeerWirePacket packet)

public PeerWirePacket Receive()
{
if (receiveQueue.TryDequeue(out var packet))
if (receiveQueue.Count > 0)
{
return packet;
return receiveQueue.Dequeue();
}

return null;
Expand Down
44 changes: 20 additions & 24 deletions bzTorrent/IO/PeerWireuTPConnection.cs
Expand Up @@ -45,24 +45,28 @@ public class PeerWireuTPConnection : IPeerConnection
private static bool receiving = false;
private byte[] currentPacketBuffer = null;
private const int socketBufferSize = 16 * 1024;
private static byte[] socketBuffer = new byte[socketBufferSize];
private static readonly byte[] socketBuffer = new byte[socketBufferSize];
private readonly Queue<PeerWirePacket> receiveQueue = new();
private readonly Queue<PeerWirePacket> sendQueue = new();
private PeerClientHandshake incomingHandshake = null;
private ushort SeqNumber = 0;
private ushort AckNumber = 0;
private uint MaxWindow = socketBufferSize;
private readonly uint MaxWindow = socketBufferSize;
private ushort ConnectionIdLocal;
private ushort ConnectionIdRemote => (ushort)(ConnectionIdLocal + 1);
private ushort ConnectionIdRemote
{
get => (ushort)(ConnectionIdLocal + 1);
}

private IPEndPoint remoteEndPoint;
private bool isConnected = false;
private bool isFullyConnected = false;
private uint LastTimestampReceived;
private uint LastTimestampReceivedDiff;

private static Dictionary<EndPoint, PeerWireuTPConnection> uTPConnections = new();
private static readonly Dictionary<EndPoint, PeerWireuTPConnection> uTPConnections = new();

private Random rng = new();
private readonly Random rng = new();

public enum PacketType : byte
{
Expand Down Expand Up @@ -91,10 +95,7 @@ public bool Connected

public PeerWireuTPConnection()
{
if (socket == null)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
socket ??= new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}

public PeerWireuTPConnection(Socket socket)
Expand All @@ -114,10 +115,7 @@ public PeerWireuTPConnection(Socket socket)
throw new ArgumentException("ProtocolType of socket must be Udp");
}

if (PeerWireuTPConnection.socket == null)
{
PeerWireuTPConnection.socket = socket;
}
PeerWireuTPConnection.socket ??= socket;
}

public void Connect(IPEndPoint endPoint)
Expand Down Expand Up @@ -169,8 +167,9 @@ public bool Process()

if (Connected)
{
while (sendQueue.TryDequeue(out var packet))
while (sendQueue.Count > 0)
{
var packet = sendQueue.Dequeue();
SendData(packet);
}
}
Expand All @@ -195,9 +194,9 @@ public void Send(PeerWirePacket packet)

public PeerWirePacket Receive()
{
if (receiveQueue.TryDequeue(out var packet))
if (receiveQueue.Count > 0)
{
return packet;
return receiveQueue.Dequeue();
}

return null;
Expand Down Expand Up @@ -295,10 +294,7 @@ private void ProcessReceivedData(byte[] socketData, int dataLengthRecvd)
socketBufferCopy = socketBufferCopy.GetBytes(protocolStrLen + 49, dataLength);
}

if (currentPacketBuffer == null)
{
currentPacketBuffer = Array.Empty<byte>();
}
currentPacketBuffer ??= Array.Empty<byte>();

currentPacketBuffer = currentPacketBuffer.Cat(socketBufferCopy.GetBytes(0, dataLength));

Expand All @@ -316,9 +312,9 @@ private static void ReceiveCallback(IAsyncResult asyncResult)
var dataLength = socket.EndReceiveFrom(asyncResult, ref endPoint);
var socketBufferCopy = socketBuffer.GetBytes(0, dataLength);

if (uTPConnections.Keys.Contains(endPoint))
if (uTPConnections.TryGetValue(endPoint, out var value))
{
var utpConnection = uTPConnections[endPoint];
var utpConnection = value;
utpConnection.ProcessReceivedData(socketBufferCopy, dataLength);
}
else
Expand Down Expand Up @@ -382,7 +378,7 @@ private uint ParsePackets(byte[] currentPacketBuffer)
return parsedBytes;
}

private PeerWirePacket ParsePacket(byte[] currentPacketBuffer)
private static PeerWirePacket ParsePacket(byte[] currentPacketBuffer)
{
var newPacket = new PeerWirePacket();

Expand All @@ -394,7 +390,7 @@ private PeerWirePacket ParsePacket(byte[] currentPacketBuffer)
return null;
}

private uint TimestampMicro()
private static uint TimestampMicro()
{
return (uint)(DateTime.UtcNow.Ticks / (TimeSpan.TicksPerMillisecond / 1000));
}
Expand Down
6 changes: 3 additions & 3 deletions bzTorrent/bzTorrent.csproj
@@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<TargetFramework>netstandard2.0</TargetFramework>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<Version>2.1.0</Version>
<Version>2.1.1</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Authors>Darren Horrocks</Authors>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
Expand All @@ -20,7 +20,7 @@
<AnalysisLevel>latest</AnalysisLevel>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="bzBencode" Version="1.0.2" />
<PackageReference Include="bzBencode" Version="1.0.4" />
</ItemGroup>
<ItemGroup>
<None Include="..\LICENSE">
Expand Down

0 comments on commit c232625

Please sign in to comment.