github.com/binkynet/BinkyNet@v1.12.1-0.20240421190447-da4e34c20be0/discovery/DiscoveryBroadcaster.cs (about)

     1  using BinkyNet.Apis.V1;
     2  using Google.Protobuf;
     3  using System;
     4  using System.IO;
     5  using System.Net;
     6  using System.Net.Sockets;
     7  using System.Threading;
     8  using System.Threading.Tasks;
     9  
    10  namespace BinkyNet.Discovery
    11  {
    12      public class DiscoveryBroadcaster
    13      {
    14          private readonly UdpClient client = new UdpClient();
    15          private readonly byte[] msgData;
    16          private CancellationTokenSource ctSource;
    17  
    18          public DiscoveryBroadcaster(NetworkMasterInfo msg)
    19          {
    20              client.EnableBroadcast = true;
    21              var ms = new MemoryStream();
    22              using (var cos = new CodedOutputStream(ms))
    23              {
    24                  msg.WriteTo(cos);
    25              }
    26              msgData = ms.ToArray();
    27          }
    28  
    29          public void Start()
    30          {
    31              if (ctSource == null)
    32              {
    33                  ctSource = new CancellationTokenSource();
    34                  startBroadcaster(ctSource.Token);
    35              }
    36          }
    37  
    38          public void Stop()
    39          {
    40              if (ctSource != null)
    41              {
    42                  ctSource.Cancel();
    43              }
    44          }
    45  
    46          public async Task startBroadcaster(CancellationToken cancellationToken)
    47          {
    48  
    49              await Task.Run(async () =>
    50              {
    51                  while (true)
    52                  {
    53                      client.EnableBroadcast = true;
    54                      client.Send(msgData, msgData.Length, new IPEndPoint(IPAddress.Broadcast, (int)Ports.Discovery));
    55                      await Task.Delay(2000, cancellationToken);
    56                      if (cancellationToken.IsCancellationRequested)
    57                          break;
    58                  }
    59              });
    60  
    61          }
    62      }
    63  }