Skip to content

Commit

Permalink
fix threading/concurrency issue in TCP connection
Browse files Browse the repository at this point in the history
  • Loading branch information
bizzehdee committed Oct 20, 2023
1 parent 35f71c7 commit b82d946
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions bzTorrent/IO/PeerWireTCPConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
using System.Text;
using System;
using System.Net;
using System.Collections.Concurrent;

namespace bzTorrent.IO
{
Expand All @@ -45,8 +46,8 @@ public class PeerWireTCPConnection : IPeerConnection
private byte[] currentPacketBuffer = null;
private const int socketBufferSize = 16 * 1024;
private readonly byte[] socketBuffer = new byte[socketBufferSize];
private readonly Queue<PeerWirePacket> receiveQueue = new();
private readonly Queue<PeerWirePacket> sendQueue = new();
private readonly ConcurrentQueue<PeerWirePacket> receiveQueue = new();
private readonly ConcurrentQueue<PeerWirePacket> sendQueue = new();
private PeerClientHandshake incomingHandshake = null;

public int Timeout
Expand Down Expand Up @@ -135,10 +136,12 @@ public bool Process()
socket.BeginReceive(socketBuffer, 0, socketBufferSize, SocketFlags.None, ReceiveCallback, this);
}

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

return Connected;
Expand All @@ -151,9 +154,9 @@ public void Send(PeerWirePacket packet)

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

return null;
Expand Down

0 comments on commit b82d946

Please sign in to comment.