public async Task <bool> TryInterceptOutgoingAsync(
            ArraySegment <byte> payload,
            EndPoint destinationEndPoint,
            IUdpClient relayClient)
        {
            if (payload.Count == 0)
            {
                throw new ArgumentException("Value cannot be an empty collection.", nameof(payload));
            }
            if (destinationEndPoint == null)
            {
                throw new ArgumentNullException(nameof(destinationEndPoint));
            }
            if (relayClient == null)
            {
                throw new ArgumentNullException(nameof(relayClient));
            }

            if (!this._randomPacketsSent)
            {
                await this.SendRandomPacketsAsync(destinationEndPoint, relayClient).ConfigureAwait(false);

                this._randomPacketsSent = true;
            }

            return(false);
        }
Esempio n. 2
0
 public DiscoveryService(
     IUdpClient networkClient,
     ILogger <DiscoveryService> logger)
 {
     NetworkClient = networkClient;
     Logger        = logger;
 }
Esempio n. 3
0
        public async Task <IReadOnlyCollection <Device> > DiscoverDevicesAsync(CancellationToken cancellationToken)
        {
            List <Device> devices = new List <Device>();

            using (IUdpClient udpClient = _udpClientFactory.Create(new IPEndPoint(IPAddress.Any, 0)))
            {
                await udpClient.SendAsync(MessageBytes, MessageBytes.Length, MulticastIpEndpoint)
                .WithCancellation(cancellationToken)
                .ConfigureAwait(false);

                UdpReceiveResult receiveResult = await udpClient.ReceiveAsync()
                                                 .WithCancellation(cancellationToken)
                                                 .ConfigureAwait(false);

                Console.WriteLine("Received a result");
                if (receiveResult.RemoteEndPoint != null)
                {
                    // We only use SSDP to discover *any* Sonos device.
                    // We then use the UPNP endpoint to discover the rest of the Sonos devices.
                    devices.AddRange(await FindDevicesFromSonosIpAddress(receiveResult.RemoteEndPoint.Address).ConfigureAwait(false));
                }
            }

            return(new ReadOnlyCollection <Device>(devices));
        }
Esempio n. 4
0
        async Task SendProbe(IUdpClient client)
        {
            var message = WSProbeMessageBuilder.NewProbeMessage();

            var multicastEndpoint = new IPEndPoint(IPAddress.Parse(Constants.WS_MULTICAST_ADDRESS), Constants.WS_MULTICAST_PORT);
            await client.SendAsync(message, message.Length, multicastEndpoint);
        }
 internal ThriftUdpClientTransport(string host, int port, MemoryStream byteStream, IUdpClient udpClient)
 {
     _host       = host;
     _port       = port;
     _byteStream = byteStream;
     _client     = udpClient;
 }
Esempio n. 6
0
 public ServerSearcher(IUdpClient client, int transPort)
 {
     remoteIpEP    = new IPEndPoint(IPAddress.Broadcast, transPort);
     commonClient  = client;
     findedIpEPs   = new Dictionary <string, IPEndPoint>();
     findingStatus = false;
 }
Esempio n. 7
0
        public UdpProxy(
            IReadOnlyTcpStream clientStream,
            IUdpClientFactory clientFactory,
            IDatagramInterceptor interceptor,
            ArrayPool <byte> bufferPool,
            ITimerFactory timerFactory,
            ILoggerFactory loggerFactory)
        {
            if (clientFactory == null)
            {
                throw new ArgumentNullException(nameof(clientFactory));
            }
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            this._clientStream = clientStream ?? throw new ArgumentNullException(nameof(clientStream));
            this._interceptor  = interceptor ?? throw new ArgumentNullException(nameof(interceptor));
            this._bufferPool   = bufferPool ?? throw new ArgumentNullException(nameof(bufferPool));

            this._boundClient = clientFactory.CreateBoundUdpClient(
                new IPEndPoint(((IPEndPoint)clientStream.LocalEndPoint).Address, 0));
            this._relayClient        = clientFactory.CreateUdpClient();
            this._reassembler        = new DatagramReassembler(timerFactory, this._bufferPool);
            this._clientEndPointTask =
                new TaskCompletionSource <EndPoint>(TaskCreationOptions.RunContinuationsAsynchronously);

            this._clientSessionTerminationSource = new CancellationTokenSource();
            this._log = loggerFactory.CreateLogger(this.GetType().Name);
            this._log.LogInformation("Started UDP listener on {0}", this.BindEndPoint);
        }
Esempio n. 8
0
        /// <summary>
        /// Construct a <see cref="UdpSink"/>.
        /// </summary>
        /// <param name="client">
        /// The UDP client responsible for sending multicast messages.
        /// </param>
        /// <param name="remoteAddress">
        /// The <see cref="IPAddress"/> of the remote host or multicast group to which the UDP
        /// client should sent the logging event.
        /// </param>
        /// <param name="remotePort">
        /// The TCP port of the remote host or multicast group to which the UDP client should sent
        /// the logging event.
        /// </param>
        /// <param name="formatter">Formatter used to convert log events to text.</param>
        public UdpSink(
            IUdpClient client,
            IPAddress remoteAddress,
            int remotePort,
            ITextFormatter formatter)
            : base(1000, TimeSpan.FromSeconds(0.5))
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }
            if (remoteAddress == null)
            {
                throw new ArgumentNullException(nameof(remoteAddress));
            }
            if (remotePort < IPEndPoint.MinPort || remotePort > IPEndPoint.MaxPort)
            {
                throw new ArgumentOutOfRangeException(nameof(remotePort));
            }
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            remoteEndPoint = new IPEndPoint(remoteAddress, remotePort);
            this.formatter = formatter;
            this.client    = client;
        }
Esempio n. 9
0
        public async Task <IEnumerable <DiscoveryDevice> > Discover(int Timeout, IUdpClient client,
                                                                    CancellationToken cancellationToken = default(CancellationToken))
        {
            var  devices = new List <DiscoveryDevice> ();
            bool isRunning;

            await SendProbe(client);

            var responses = new List <UdpReceiveResult> ();

            try {
                isRunning = true;
                var cts = new CancellationTokenSource(TimeSpan.FromSeconds(Timeout));
                while (isRunning)
                {
                    if (cts.IsCancellationRequested || cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }
                    var response = await client.ReceiveAsync().WithCancellation(cts.Token).WithCancellation(cancellationToken);

                    responses.Add(response);
                }
            } catch (OperationCanceledException) {
                isRunning = false;
            } finally {
                client.Close();
            }
            if (cancellationToken.IsCancellationRequested)
            {
                return(devices);
            }
            devices.AddRange(ProcessResponses(responses));
            return(devices);
        }
Esempio n. 10
0
        public void UseDualModeOnInterNetworkV6()
        {
            // Act
            client = UdpClientFactory.Create(0, AddressFamily.InterNetworkV6);

            // Assert
            client.Client.DualMode.ShouldBeTrue();
        }
Esempio n. 11
0
        public GamePadClient(IUdpClient udpClient, IPlatform platform) : base(udpClient, platform)
        {
            udpClient.CreateWithEmptyEndPoint();
            BroadCastEndPoint = udpClient.GetBroadCastEndPoint(Defaults.DEFAULT_SERVER_PORT);

            // TODO: Change this to a proper identity
            PlayerIdentity = PlayerIdentity.GenerateNew("Test Player");
        }
Esempio n. 12
0
 public RoundTripTimeService(IUdpClient udpClient, NetworkTimeService networkTimeService)
 {
     this.udpClient          = udpClient;
     this.networkTimeService = networkTimeService;
     this.udpClient.OnMessageReceive
     .Where(message => message[0] == MessageId.PING_RESP)
     .Subscribe(OnMessageReceived);
 }
Esempio n. 13
0
 public Connection(IPEndPoint receiveEndPoint, IPEndPoint sendEndPoint, IKnxReceiveParserDispatcher receiveParserDispatcher, IUdpClient udpClient)
 {
     _receiveEndPoint         = receiveEndPoint;
     _receiveParserDispatcher = receiveParserDispatcher;
     _sendEndPoint            = sendEndPoint;
     _udpClient = udpClient;
     ProcessSendMessages();
 }
Esempio n. 14
0
 public DiscoveryMessageListener(
     IUdpClient client,
     IIncomingMessageDispatcher dispatcher,
     ILogger <DiscoveryMessageListener> logger)
 {
     UdpClient  = client;
     Dispatcher = dispatcher;
     Logger     = logger;
 }
Esempio n. 15
0
 public void SendMessage(IUdpClient udpClient, LifxMessage message, IPEndPoint endpoint)
 {
     using (var memoryStream = new MemoryStream())
     {
         message.WriteToStream(memoryStream);
         byte[] packet = memoryStream.ToArray();
         udpClient.SendAsync(packet, packet.Length, endpoint.Address.ToString(), endpoint.Port);
     }
 }
Esempio n. 16
0
        //Sender(string ra, int rp, IPackage p)
        //{
        //    this.RemoteAdress = ra;
        //    this.RemotePort = rp;
        //    this.Pack = p;
        //}

        //public Sender() { }

        public SenderUdpClientBased(INetCommunicationObj withCommunicationObj)
        {
            IUdpClient cl = withCommunicationObj as IUdpClient;

            if (cl == null)
            {
                throw new Exception("Invalid constructor parameter..");
            }
            _lockal_udp_client = cl.NetClient;
        }
Esempio n. 17
0
 public UdpSink(
     IUdpClient client,
     string remoteAddress,
     int remotePort,
     ITextFormatter formatter)
 {
     this.client    = client ?? throw new ArgumentNullException(nameof(client));
     remoteEndPoint = new RemoteEndPoint(remoteAddress, remotePort);
     this.formatter = formatter ?? throw new ArgumentNullException(nameof(formatter));
 }
Esempio n. 18
0
 public MatchSimulation(byte localPlayerUnitId, Int64 matchStartTimestamp, MatchInputProvider matchInputProvider,
                        MatchSpawnService matchEventProvider, IUdpClient udpClient, NetworkTimeService networkTimeService)
 {
     this.localPlayerUnitId   = localPlayerUnitId;
     this.matchStartTimestamp = matchStartTimestamp;
     inputProvider            = matchInputProvider;
     eventProvider            = matchEventProvider;
     this.udpClient           = udpClient;
     this.networkTimeService  = networkTimeService;
     SimulationFrameSubject   = new Subject <byte>();
 }
Esempio n. 19
0
 public LoginServerClient(ISessionRecivedHandler sessionRecivedHandler,
                          ISystemMessage systemMessage,
                          ILogger logger, IUdpClient udpClient,
                          ISoeActionFactory soeActionFactory)
 {
     _soeActionFactory      = soeActionFactory;
     _sessionRecivedHandler = sessionRecivedHandler;
     _systemMessage         = systemMessage;
     _logger    = logger;
     _udpClient = udpClient;
     _eventHandler.UdpPacketsRecived += TryHandleInncommingPacket;
 }
Esempio n. 20
0
        public void Synch(IUdpClient udpClient, Action onTimeSynched = null)
        {
            currentOnTimeSynchedCallback = onTimeSynched;
            responsesReceived            = 0;

            this.udpClient = udpClient;

            messageReceiveDisposable = udpClient.OnMessageReceive
                                       .Where(message => message[0] == MessageId.TIME_RESP)
                                       .Subscribe(OnMessageReceived);

            SendTimeSynchMessage();
        }
Esempio n. 21
0
        internal DatagramSender(DatagramDispatcher dispatcher)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher");
            }

            this.lastCommandSequenceNumber = -1;
            this.LastCommandSentTime = DateTime.Now.Subtract(dispatcher.KeepAlivePeriod).AddSeconds(5);
            this.Metrics = dispatcher.Metrics;
            this.responseDispatcher = dispatcher.ResponseDispatcher;
            this.udpClient = dispatcher.UdpClient;
            this.Log = LogManager.GetLogger(this.GetType());
        }
Esempio n. 22
0
        public GamePadServer(IUdpClient udpClient, IPlatform platform, String serverName, String serverPassword = "", int capacity = Defaults.DEFAULT_SERVER_CAPACITY, int listeningPort = Defaults.DEFAULT_SERVER_PORT) : base(udpClient, platform)
        {
            if (!ValidateServerName(serverName))
            {
                throw new BonaVirtualGamePadException("Server name contains disallowed characters");
            }

            ServerName     = serverName;
            ServerPassword = serverPassword;

            ListeningEndPoint = UdpClient.GetAnyEndPoint(listeningPort);
            UdpClient.SetEndPoint(ListeningEndPoint);

            Clients = new PlayerClient[capacity];
        }
 /// <summary>
 /// Start listening for requests
 /// </summary>
 public void Start()
 {
     if (!Running)
     {
         _server = _udpClientFactory.CreateClient(_localEndpoint);
         Running = true;
         _log.Info($"Starting Radius server on {_localEndpoint}");
         var receiveTask = StartReceiveLoopAsync();
         _log.Info("Server started");
     }
     else
     {
         _log.Warn("Server already started");
     }
 }
Esempio n. 24
0
        public MainPageViewModel(IUdpServer udpServer, IUdpClient udpClient, IWlanClient wlanClient)
        {
            _udpServer  = udpServer;
            _udpClient  = udpClient;
            _wlanClient = wlanClient;

            _udpServer.NewDataReceiveEvent += UdpServerOnNewDataReceiveEvent;
            _udpClient.StatusEvent         += UdpClientOnStatusEvent;

            StartCommand = new MvxCommand(StartCommandHander);
            StopCommand  = new MvxCommand(StopCommandHander);

            ShouldAlwaysRaiseInpcOnUserInterfaceThread(false); //Mvx需要关闭必须UI线程刷新

            TrySetSSID();
        }
Esempio n. 25
0
        /// <summary>
        /// Free resources held by the sink.
        /// </summary>
        /// <param name="disposing">
        /// If true, called because the object is being disposed; if false, the object is being
        /// disposed from the finalizer.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing && client != null)
            {
#if NET4
                // UdpClient does not implement IDisposable, but calling Close disables the
                // underlying socket and releases all managed and unmanaged resources associated
                // with the instance.
                client.Close();
#else
                client.Dispose();
#endif
                client = null;
            }
        }
        async Task SendRandomPacketsAsync(EndPoint destinationEndPoint, IUdpClient relayClient)
        {
            var settings = this._settings;

            var randomPacketCount = this._random.Next(
                settings.CountMin,
                settings.CountMax);

            var randomPacketBuffer = this._bufferPool.Rent(settings.BytesMax);

            try
            {
                for (var i = 0; i < randomPacketCount; i++)
                {
                    this._random.NextBytes(randomPacketBuffer);

                    var randomSize = this._random.Next(
                        settings.BytesMin,
                        settings.BytesMax);

                    var randomDelay = this._random.Next(
                        settings.DelayMsMin,
                        settings.DelayMsMax);

                    await Task.Delay(randomDelay).ConfigureAwait(false);

                    this._log.LogDebug(
                        "Sending random packet {0}/{1}: {2} bytes delayed {3}ms",
                        i + 1,
                        randomPacketCount,
                        randomSize,
                        randomDelay);

                    await relayClient
                    .SendAsync(randomPacketBuffer, 0, randomSize, destinationEndPoint)
                    .ConfigureAwait(false);
                }
            }
            finally
            {
                this._bufferPool.Return(randomPacketBuffer);
            }
        }
Esempio n. 27
0
        public Z21Client(IUdpClient udpClient)
        {
            this.udpClient = udpClient;
            inStream       = udpClient.ObserveBytes();

            var connectionTicker = Observable.Interval(TimeSpan.FromSeconds(2))
                                   .SelectMany(async x => {
                try {
                    await GetSerialNumber(new SerialNumberRequest());
                    return(true);
                } catch (TimeoutException) {
                    return(false);
                }
            })
                                   .Publish();

            keepConnectionAliveSubscription = connectionTicker.Connect();
            ConnectionStatus = connectionTicker.DistinctUntilChanged();
        }
Esempio n. 28
0
        internal static LifxMessage FromPacket(byte[] data, IUdpClient respondClient)
        {
            using (MemoryStream ms = new MemoryStream(data))
            {
                var headerBytes = new byte[36];
                Array.Copy(data, headerBytes, headerBytes.Length);

                var header = LifxHeader.FromHeaderBytes(headerBytes);

                byte[] payload = null;
                if (data.Length > 36)
                {
                    payload = new byte[data.Length - 36];
                    Array.Copy(data, 36, payload, 0, payload.Length);
                }

                return(LifxMessage.FromPayloadBytes(header, payload, respondClient));
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DnsSeedServer"/> class with the port to listen on.
        /// </summary>
        /// <param name="client">The UDP client to use to receive DNS requests and send DNS responses.</param>
        /// <param name="masterFile">The initial DNS masterfile.</param>
        /// <param name="asyncLoopFactory">The async loop factory.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="dateTimeProvider">The <see cref="DateTime"/> provider.</param>
        /// <param name="nodeSettings">The node settings object containing node configuration.</param>
        /// <param name="dataFolders">The data folders of the system.</param>
        public DnsSeedServer(IUdpClient client, IMasterFile masterFile, IAsyncLoopFactory asyncLoopFactory, INodeLifetime nodeLifetime, ILoggerFactory loggerFactory, IDateTimeProvider dateTimeProvider, DnsSettings dnsSettings, DataFolder dataFolders)
        {
            Guard.NotNull(client, nameof(client));
            Guard.NotNull(masterFile, nameof(masterFile));
            Guard.NotNull(asyncLoopFactory, nameof(asyncLoopFactory));
            Guard.NotNull(nodeLifetime, nameof(nodeLifetime));
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(dateTimeProvider, nameof(dateTimeProvider));
            Guard.NotNull(dnsSettings, nameof(dnsSettings));
            Guard.NotNull(dataFolders, nameof(dataFolders));

            this.udpClient        = client;
            this.masterFile       = masterFile;
            this.asyncLoopFactory = asyncLoopFactory;
            this.nodeLifetime     = nodeLifetime;
            this.logger           = loggerFactory.CreateLogger(this.GetType().FullName);
            this.dateTimeProvider = dateTimeProvider;
            this.dnsSettings      = dnsSettings;
            this.dataFolders      = dataFolders;
            this.metrics          = new DnsMetric();
        }
Esempio n. 30
0
        public async void SendPayload(string address, AddressFamily family)
        {
            // Arrange
            client = UdpClientFactory.Create(0, family);

            var ipAddress = IPAddress.Parse(address);

            using (var server = new UdpClient(0, ipAddress.AddressFamily))
            {
                var receiveTask = server.ReceiveAsync();

                // Act
                await client.SendAsync(
                    PayloadAsBytes,
                    PayloadAsBytes.Length,
                    new IPEndPoint(ipAddress, ((IPEndPoint)server.Client.LocalEndPoint).Port));

                // Assert
                var receivedData = (await receiveTask).Buffer;
                Encoding.UTF8.GetString(receivedData).ShouldBe(Payload);
            }
        }
 public Task <bool> TryInterceptIncomingAsync(Datagram datagram, IUdpClient boundClient)
 {
     return(CachedTasks.FalseTask);
 }
Esempio n. 32
0
 internal RConClient(IUdpClient client, string password)
 {
     this.UdpClient = client;
     this.password = password;
     this.Initialize();
 }