Skip to content

Commit

Permalink
网络多线程, 一个客户端一个线程
Browse files Browse the repository at this point in the history
  • Loading branch information
SlimeNull committed Jun 25, 2024
1 parent 9fb0348 commit 1a4eb7e
Showing 1 changed file with 21 additions and 32 deletions.
53 changes: 21 additions & 32 deletions Sn.ScreenBroadcaster/Views/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
Expand Down Expand Up @@ -340,7 +341,6 @@ private void Start()
BroadcastTask = Task.WhenAll(
NetworkLoop(),
CaptureLoop(),
BroadcastLoop(),
StatusLoop()
);
}
Expand Down Expand Up @@ -454,7 +454,10 @@ _cancellationTokenSource is null ||

lock (_clients)
{
_clients.Add(new TcpClientInfo(newClient, new()));
var newClientInfo = new TcpClientInfo(newClient, new());

_clients.Add(newClientInfo);
_ = BroadcastLoop(newClientInfo);
}

Dispatcher.Invoke(() =>
Expand Down Expand Up @@ -689,7 +692,7 @@ _videoEncoder is null ||
});
}

private Task BroadcastLoop()
private Task BroadcastLoop(TcpClientInfo clientInfo)
{
return Task.Run(() =>
{
Expand All @@ -701,40 +704,26 @@ private Task BroadcastLoop()

while (!cancellationToken.IsCancellationRequested)
{
lock (_clients)
while (clientInfo.Frames.Count > CountForDroppingFrame &&
(ThrowsKeyFrame || clientInfo.Frames.Count(v => v.IsKeyFrame) > 2))
{
clientsToRemove.Clear();
foreach (var client in _clients)
{
while (client.Frames.Count > CountForDroppingFrame &&
(ThrowsKeyFrame || client.Frames.Count(v => v.IsKeyFrame) > 2))
{
client.Frames.TryDequeue(out _);
}

if (client.Frames.TryDequeue(out var frameData))
{
try
{
var stream = client.TcpClient.GetStream();
frameData.WriteToStream(stream);
}
catch
{
clientsToRemove.Add(client);
}
}
}

bool clientsHasChange = clientsToRemove.Count != 0;
clientInfo.Frames.TryDequeue(out _);
}

foreach (var client in clientsToRemove)
if (clientInfo.Frames.TryDequeue(out var frameData))
{
try
{
_clients.Remove(client);
var stream = clientInfo.TcpClient.GetStream();
frameData.WriteToStream(stream);
}

if (clientsHasChange)
catch
{
lock(_clients)
{
_clients.Remove(clientInfo);
}

Dispatcher.Invoke(() =>
{
ConnectedClients = _clients
Expand Down

0 comments on commit 1a4eb7e

Please sign in to comment.