public void ShouldSendLongUdpMessage()
            {
                var jsonObject = new JObject();
                var message    = ResourceHelper.GetResource("LongMessage.txt").ReadToEnd();

                jsonObject.Add("message", JToken.FromObject(message));

                var converter = new Mock <IConverter>();

                converter.Setup(c => c.GetLogEventJson(It.IsAny <LogEventInfo>())).Returns(jsonObject).Verifiable();
                var transportClient = new Mock <ITransportClient>();

                transportClient.Setup(t => t.Send(It.IsAny <byte[]>(), It.IsAny <Int32>(), It.IsAny <IPEndPoint>())).Verifiable();

                var transport = new UdpTransport(transportClient.Object);
                var dnslookup = new Mock <DnsBase>();

                dnslookup.Setup(x => x.GetHostAddresses(It.IsAny <string>())).Returns(new[] { IPAddress.Parse("127.0.0.1") });
                var target = new NetworkJsonTarget(new[] { transport }, converter.Object, dnslookup.Object)
                {
                    Endpoint = "udp://127.0.0.1:12201"
                };

                target.WriteLogEventInfo(new LogEventInfo());

                transportClient.Verify(t => t.Send(It.IsAny <byte[]>(), It.IsAny <Int32>(), It.IsAny <IPEndPoint>()), Times.Once());
                converter.Verify(c => c.GetLogEventJson(It.IsAny <LogEventInfo>()), Times.Once());
            }
        public void WhenSend_ThenCallMethods()
        {
            var transportClient      = new Mock <ITransportClient <byte[]> >();
            var dataToChunkConverter = new Mock <IDataToChunkConverter>();
            var fixture = new Fixture();

            var stringData = fixture.Create <string>();

            byte[] data = stringData.Compress();

            List <byte[]> chunks = fixture.CreateMany <byte[]>(3).ToList();

            dataToChunkConverter.Setup(c => c.ConvertToChunks(data)).Returns(chunks);

            UdpTransport target = new UdpTransport(transportClient.Object, dataToChunkConverter.Object);

            target.Send(stringData);

            dataToChunkConverter.Verify(c => c.ConvertToChunks(data), Times.Once);

            foreach (byte[] chunk in chunks)
            {
                transportClient.Verify(c => c.Send(chunk), Times.Once);
            }
        }
        public ITransport MakeTransport()
        {
            switch (_options.TransportType)
            {
            case SinkTransportType.Udp:

                IDnsInfoProvider dns        = new DnsWrapper();
                IPAddress[]      ipAddreses = Task.Run(() => dns.GetHostAddresses(_options.HostnameOrAddress)).Result;
                IPAddress        ipAddress  = ipAddreses.FirstOrDefault(c => c.AddressFamily == AddressFamily.InterNetwork);

                var ipEndpoint = new IPEndPoint(ipAddress ?? throw new InvalidOperationException(), _options.Port);


                var chunkSettings = new ChunkSettings(_options.MessageGeneratorType, _options.MaxMessageSizeInUdp);
                IDataToChunkConverter chunkConverter = new DataToChunkConverter(chunkSettings, new MessageIdGeneratorResolver());

                var udpClient    = new UdpTransportClient(ipEndpoint);
                var udpTransport = new UdpTransport(udpClient, chunkConverter);
                return(udpTransport);

            case SinkTransportType.Http:
                var httpClient    = new HttpTransportClient($"{_options.HostnameOrAddress}:{_options.Port}/gelf");
                var httpTransport = new HttpTransport(httpClient);
                return(httpTransport);

            default:
                throw new ArgumentOutOfRangeException(nameof(_options), _options.TransportType, null);
            }
        }
예제 #4
0
            public void ShouldSendLongUdpMessage()
            {
                var jsonObject = new JObject();
                var message    = ResourceHelper.GetResource("LongMessage.txt").ReadToEnd();

                jsonObject.Add("full_message", JToken.FromObject(message));

                var converter = new Mock <IConverter>();

                converter.Setup(c => c.GetGelfJson(It.IsAny <LogEventInfo>(), It.IsAny <string>())).Returns(jsonObject).Verifiable();
                var transportClient = new Mock <ITransportClient>();

                transportClient.Setup(t => t.Send(It.IsAny <byte[]>(), It.IsAny <Int32>(), It.IsAny <IPEndPoint>())).Verifiable();

                var transport = new UdpTransport(transportClient.Object);

                var target = new NLogTarget(transport, converter.Object)
                {
                    HostIp = "127.0.0.1"
                };

                target.WriteLogEventInfo(new LogEventInfo());

                transportClient.Verify(t => t.Send(It.IsAny <byte[]>(), It.IsAny <Int32>(), It.IsAny <IPEndPoint>()), Times.Exactly(4));
                converter.Verify(c => c.GetGelfJson(It.IsAny <LogEventInfo>(), It.IsAny <string>()), Times.Once());
            }
예제 #5
0
        public void ConversationSendAndReceive()
        {
            IPEndPoint initiatorEndpoint = new IPEndPoint(IPAddress.Loopback, 6789);
            IPEndPoint responderEndpoint = new IPEndPoint(IPAddress.Loopback, 6788);

            UdpTransport initiatorCommunicator = new UdpTransport(initiatorEndpoint.Port);
            UdpTransport responderCommunicator = new UdpTransport(responderEndpoint.Port);

            SimpleRequestReplyInitiator convInitiator = new SimpleRequestReplyInitiator(initiatorCommunicator, responderEndpoint);
            SimpleRequestReplyResponder convResponder = new SimpleRequestReplyResponder(responderCommunicator);

            Assert.AreNotEqual(convResponder.Id, convInitiator.Id);
            Assert.IsFalse(ConversationManager.ConversationDictionary.ContainsKey(convInitiator.Id));
            Assert.IsFalse(ConversationManager.ConversationDictionary.ContainsKey(convResponder.Id));
            Assert.IsFalse(convResponder.IsActive);
            Assert.IsFalse(convInitiator.IsActive);

            convResponder.Start();
            convInitiator.Start();

            Thread.Sleep(5000);
            Assert.IsTrue(convResponder.IsActive);
            Assert.IsTrue(convInitiator.IsActive);
            Assert.IsNotNull(convInitiator.SentMessage);
            Assert.IsNotNull(convResponder.ReceivedMessage);
            Assert.AreNotEqual(convResponder.ReceivedMessages.Count, 0);

            Thread.Sleep(5000);
            Assert.IsNotNull(convResponder.SentMessage);
            Assert.IsNotNull(convInitiator.ReceivedMessage);
            Assert.AreNotEqual(convInitiator.ReceivedMessages.Count, 0);
        }
예제 #6
0
        private ITransport MakeTransport(GraylogSinkOptions options)
        {
            switch (options.TransportType)
            {
            case SerilogTransportType.Udp:

                IDnsInfoProvider dns        = new DnsWrapper();
                IPAddress[]      ipAddreses = Task.Run(() => dns.GetHostAddresses(options.HostnameOrAddress)).Result;
                IPAddress        ipAddress  = ipAddreses.FirstOrDefault(c => c.AddressFamily == AddressFamily.InterNetwork);
                var ipEndpoint = new IPEndPoint(ipAddress, options.Port);

                IDataToChunkConverter chunkConverter = new DataToChunkConverter(new ChunkSettings
                {
                    MessageIdGeneratorType = options.MessageGeneratorType
                }, new MessageIdGeneratorResolver());

                var udpClient    = new UdpTransportClient(ipEndpoint);
                var udpTransport = new UdpTransport(udpClient, chunkConverter);
                return(udpTransport);

            case SerilogTransportType.Http:
                var httpClient    = new HttpTransportClient($"{options.HostnameOrAddress}:{options.Port}/gelf");
                var httpTransport = new HttpTransport(httpClient);
                return(httpTransport);

            default:
                throw new ArgumentOutOfRangeException(nameof(options), options.TransportType, null);
            }
        }
예제 #7
0
            public void AmountOfChunksTest(int bufferLength, int expectedChunksCount)
            {
                // arrange
                var buffer = new byte[bufferLength];

                // act
                var chunksCount = UdpTransport.CreateChunks(buffer).Count();

                // assert
                chunksCount.Should().Be(expectedChunksCount);
            }
예제 #8
0
        public void TestMessageId()
        {
            // Arrange
            string hostName = "localhost";

            // Act
            string actual = new UdpTransport().GenerateMessageId(hostName);

            // Assert
            const int expectedLength = 8;

            Assert.AreEqual(actual.Length, expectedLength);
        }
예제 #9
0
        public void CreateChunkedMessagePart_Always_IndexIsSmallerThanChuckCount()
        {
            // Arrange
            string messageId  = "A1B2C3D4";
            int    index      = 1;
            int    chunkCount = 2;

            // Act
            byte[] result = new UdpTransport().CreateChunkedMessagePart(messageId, index, chunkCount);

            // Assert
            Assert.That(result[10], Is.LessThanOrEqualTo(result[11]));
        }
예제 #10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Thread.Sleep(1000);
            var sw = Stopwatch.StartNew();
            //for(int i = 0; i< 10; i++)
            int SocketCount  = 1;
            int PackageCount = 500;

            for (int i = 0; i < SocketCount; i++)
            {
                new Thread(() =>
                {
                    var conv                  = (uint)(i);
                    UdpTransport client       = new UdpTransport(conv);
                    client.OnMessageReceived += (obj, buf) =>
                    {
                        var cnt = Interlocked.Increment(ref ReceivedCount);
                        if (cnt == SocketCount * PackageCount)
                        {
                            sw.Stop();
                            Console.WriteLine("over");
                        }
                        string message = Encoding.UTF8.GetString(buf.Span);
                        Console.WriteLine("[收到]" + message);
                    };
                    client.Connect("127.0.0.1", 2020);

                    //Thread.Sleep(1000);
                    for (int x = 0; x < PackageCount; x++)
                    {
                        var str = $"[{conv}] {x}";
                        client.SendMsg(Encoding.UTF8.GetBytes(str));
                        Thread.Sleep(1000);
                    }
                }).Start();
            }

            while (true)
            {
                var str = Console.ReadLine();
                if (str == "q")
                {
                    break;
                }

                Console.WriteLine("收到总:{0}, 用时{1}", ReceivedCount, sw.ElapsedMilliseconds);
            }

            Console.WriteLine("byebye");
        }
예제 #11
0
        public void CreateChunkedMessagePart_StartsWithCorrectHeader()
        {
            // Arrange
            string messageId  = "A1B2C3D4";
            int    index      = 1;
            int    chunkCount = 1;

            // Act
            byte[] result = new UdpTransport().CreateChunkedMessagePart(messageId, index, chunkCount);

            // Assert
            Assert.That(result[0], Is.EqualTo(30));
            Assert.That(result[1], Is.EqualTo(15));
        }
예제 #12
0
        public void CreateChunkedMessagePart_EndsWithIndexAndCount()
        {
            // Arrange
            string messageId  = "A1B2C3D4";
            int    index      = 1;
            int    chunkCount = 2;

            // Act
            byte[] result = new UdpTransport().CreateChunkedMessagePart(messageId, index, chunkCount);

            // Assert
            Assert.That(result[10], Is.EqualTo(index));
            Assert.That(result[11], Is.EqualTo(chunkCount));
        }
예제 #13
0
        public void Setup()
        {
            var config = new StatsDConfiguration
            {
                Host = "127.0.0.1",
            };

            var endpointSource = EndpointParser.MakeEndPointSource(
                config.Host,
                config.Port,
                config.DnsLookupInterval);

            _pooledTransport   = new PooledUdpTransport(endpointSource);
            _unpooledTransport = new UdpTransport(endpointSource);
        }
        private static ITransport CreateSyncUdpTransport(GraylogSinkOptions options)
        {
            var chunkConverter = new DataToChunkConverter(new ChunkSettings
            {
                MessageIdGeneratorType = options.MessageGeneratorType
            }, new MessageIdGeneratorResolver());

            var udpTransport = new UdpTransport(
                chunkConverter,
                options.HostnameOrAddress,
                options.Port,
                options.UdpClientFactory
                );

            return(udpTransport);
        }
        public ITransport MakeTransport()
        {
            switch (_options.TransportType)
            {
            case SinkTransportType.Udp:
            {
                var ipAddress  = Task.Run(() => GetIpAddress(_options.HostnameOrAddress)).GetAwaiter().GetResult();
                var ipEndpoint = new IPEndPoint(ipAddress ?? throw new InvalidOperationException(), _options.Port.GetValueOrDefault(12201));


                var chunkSettings = new ChunkSettings(_options.MessageGeneratorType, _options.MaxMessageSizeInUdp);
                IDataToChunkConverter chunkConverter =
                    new DataToChunkConverter(chunkSettings, new MessageIdGeneratorResolver());

                var udpClient    = new UdpTransportClient(ipEndpoint);
                var udpTransport = new UdpTransport(udpClient, chunkConverter);
                return(udpTransport);
            }

            case SinkTransportType.Http: {
                var builder = new UriBuilder(_options.HostnameOrAddress)
                {
                    Port = _options.Port.GetValueOrDefault(12201),
                    Path = "gelf"
                };

                var httpClient = new HttpTransportClient(builder.Uri.ToString());

                var httpTransport = new HttpTransport(httpClient);
                return(httpTransport);
            }

            case SinkTransportType.Tcp:
            {
                var ipAddress = Task.Run(() => GetIpAddress(_options.HostnameOrAddress)).GetAwaiter().GetResult();
                var tcpClient = new TcpTransportClient(ipAddress, _options.Port.GetValueOrDefault(12201), _options.UseSsl ? _options.HostnameOrAddress : null);
                var transport = new TcpTransport(tcpClient);
                return(transport);
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(_options), _options.TransportType, null);
            }
        }
예제 #16
0
        private static void Main(string[] args)
        {
            var iterations = Enumerable.Range(1, 500000);
            var endpoint   = EndpointParser.MakeEndPointSource("localhost", 3128, null);
            var client     = new UdpTransport(endpoint);
            var formatter  = new StatsDMessageFormatter(CultureInfo.InvariantCulture);
            var watch      = new Stopwatch();

            Console.WriteLine("To start - hit ENTER.");
            Console.ReadLine();
            Console.WriteLine("start");
            watch.Start();

            Parallel.ForEach(iterations, x => client.Send(formatter.Gauge(x, "bucket_sample" + "number-of-messages-to-be-sent")));

            watch.Stop();
            Console.WriteLine("end - " + watch.ElapsedMilliseconds);
            Console.ReadLine();
        }
예제 #17
0
        public UdpTransportTest()
        {
            LogFactory.Assign(new ConsoleLogFactory(null));

            var headerFactory = new HeaderFactory();

            headerFactory.AddDefaultParsers();
            _messageFactory = new MessageFactory(headerFactory);
            _messageFactory.RequestReceived  += OnRequest;
            _messageFactory.ResponseReceived += OnResponse;
            var pool = new ObjectPool <byte[]>(CreateBuffer);

            _transport = new UdpTransport(new IPEndPoint(IPAddress.Loopback, PortNumber), _messageFactory)
            {
                BufferPool = _bufferPool
            };
            _transport.Start();
            _transport.UnhandledException += OnUnhandledException;
        }
예제 #18
0
        public void CreateChunkedMessagePart_ContainsMessageId()
        {
            // Arrange
            string messageId  = "A1B2C3D4";
            int    index      = 1;
            int    chunkCount = 1;

            // Act
            byte[] result = new UdpTransport().CreateChunkedMessagePart(messageId, index, chunkCount);

            // Assert
            Assert.That(result[2], Is.EqualTo((int)'A'));
            Assert.That(result[3], Is.EqualTo((int)'1'));
            Assert.That(result[4], Is.EqualTo((int)'B'));
            Assert.That(result[5], Is.EqualTo((int)'2'));
            Assert.That(result[6], Is.EqualTo((int)'C'));
            Assert.That(result[7], Is.EqualTo((int)'3'));
            Assert.That(result[8], Is.EqualTo((int)'D'));
            Assert.That(result[9], Is.EqualTo((int)'4'));
        }
      public Task<ITransport> CreateAsync(MobOperations mobOperations, Identity identity, RoutingTable routingTable, PeerTable peerTable, InboundMessageDispatcher inboundMessageDispatcher, AuditService auditService) {
         // setup identity
         identity.Properties[UdpConstants.kUnicastPortIdentityPropertyKey] = configuration.UnicastReceiveEndpoint.Port.ToString();

         var duplicateFilter = new DuplicateFilter();
         duplicateFilter.Initialize();

         var inboundBytesAggregator = auditService.GetAggregator<double>(DataSetNames.kInboundBytes);
         var outboundBytesAggregator = auditService.GetAggregator<double>(DataSetNames.kOutboundBytes);
         var inboundReceiveProcessDispatchLatencyAggregator = auditService.GetAggregator<double>(DataSetNames.kInboundProcessDispatchLatency);
         var resendsCounter = auditService.GetCounter(DataSetNames.kTotalResends);
         var resendsAggregator = auditService.GetAggregator<int>(DataSetNames.kMessageResends);
         var tossedCounter = auditService.GetCounter(DataSetNames.kTossed);
         var duplicatesReceivedCounter = auditService.GetCounter(DataSetNames.kDuplicatesReceived);
         var announcementsReceivedCounter = auditService.GetCounter(DataSetNames.kAnnouncementsReceived);
         var multiPartChunksSentCounter = auditService.GetCounter(DataSetNames.kMultiPartChunksSent);
         var multiPartChunksReceivedAggregator = auditService.GetAggregator<int>(DataSetNames.kMultiPartChunksBytesReceived);
         var outboundMessageRateLimitAggregator = auditService.GetAggregator<double>(DataSetNames.kOutboundMessageRateLimit);
         var sendQueueDepthAggregator = auditService.GetAggregator<double>(DataSetNames.kSendQueueDepth);

         mobOperations.RegisterMob(new UdpDebugMob());

         var shutdownCts = new CancellationTokenSource();
         var acknowledgementCoordinator = new AcknowledgementCoordinator(identity);
         var udpUnicastScheduler = SchedulerFactory.CreateWithCustomThreadPool($"Courier.Udp({identity.Id.ToShortString()}).Unicast");
         var sendReceiveBufferPool = ObjectPool.CreateStackBacked(() => new byte[UdpConstants.kMaximumTransportSize]);
         var client = UdpClient.Create(configuration, udpUnicastScheduler, sendReceiveBufferPool, inboundBytesAggregator, outboundBytesAggregator, inboundReceiveProcessDispatchLatencyAggregator);
         var payloadSender = new PayloadSender(client);
         var multiPartPacketReassembler = new MultiPartPacketReassembler();
         var udpUnicasterFactory = new UdpUnicasterFactory(identity, client, acknowledgementCoordinator, sendReceiveBufferPool, resendsCounter, resendsAggregator, outboundMessageRateLimitAggregator, sendQueueDepthAggregator);
         var udpDispatcher = new UdpDispatcherImpl(identity, client, duplicateFilter, payloadSender, acknowledgementCoordinator, routingTable, peerTable, inboundMessageDispatcher, multiPartPacketReassembler, udpUnicasterFactory, announcementsReceivedCounter, tossedCounter, duplicatesReceivedCounter, multiPartChunksReceivedAggregator);
         multiPartPacketReassembler.SetUdpDispatcher(udpDispatcher);
         var announcer = new Announcer(identity, payloadSender, shutdownCts.Token);
         announcer.Initialize();
         var udpFacade = new UdpFacade(client, udpDispatcher, shutdownCts);
         var udpBroadcaster = new UdpBroadcaster(identity, client);
         var transport = new UdpTransport(udpBroadcaster, udpFacade);
         client.StartReceiving(udpDispatcher);

         return Task.FromResult<ITransport>(transport);
      }
예제 #20
0
        /// <summary>
        /// Connect to a group to start streaming
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="simulator"></param>
        /// <returns></returns>
        public async Task Connect(string groupId, bool simulator = false)
        {
            _simulator = simulator;
            var enableResult = await _localHueClient.SetStreamingAsync(groupId).ConfigureAwait(false);

            byte[] psk = FromHex(_clientKey);
            BasicTlsPskIdentity pskIdentity = new BasicTlsPskIdentity(_appKey, psk);

            var dtlsClient = new DtlsClient(null !, pskIdentity);

            DtlsClientProtocol clientProtocol = new DtlsClientProtocol(new SecureRandom());

            await _socket.ConnectAsync(IPAddress.Parse(_ip), 2100).ConfigureAwait(false);

            _udp = new UdpTransport(_socket);

            if (!simulator)
            {
                _dtlsTransport = clientProtocol.Connect(dtlsClient, _udp);
            }
        }
예제 #21
0
            public void ShouldSendShortUdpMessage()
            {
                var transportClient = new Mock <ITransportClient>();
                var transport       = new UdpTransport(transportClient.Object);
                var converter       = new Mock <IConverter>();

                converter.Setup(c => c.GetGelfJson(It.IsAny <LogEventInfo>(), It.IsAny <string>())).Returns(new JObject());

                var target = new NLogTarget(transport, converter.Object)
                {
                    HostIp = "127.0.0.1"
                };
                var logEventInfo = new LogEventInfo {
                    Message = "Test Message"
                };

                target.WriteLogEventInfo(logEventInfo);

                transportClient.Verify(t => t.Send(It.IsAny <byte[]>(), It.IsAny <Int32>(), It.IsAny <IPEndPoint>()), Times.Once());
                converter.Verify(c => c.GetGelfJson(It.IsAny <LogEventInfo>(), It.IsAny <string>()), Times.Once());
            }
        public ITransport MakeTransport()
        {
            switch (_options.TransportType)
            {
            case SinkTransportType.Udp:
            {
                var ipAddress  = Task.Run(() => GetIpAddress(_options.HostnameOrAddress)).GetAwaiter().GetResult();
                var ipEndpoint = new IPEndPoint(ipAddress ?? throw new InvalidOperationException(), _options.Port);


                var chunkSettings = new ChunkSettings(_options.MessageGeneratorType, _options.MaxMessageSizeInUdp);
                IDataToChunkConverter chunkConverter =
                    new DataToChunkConverter(chunkSettings, new MessageIdGeneratorResolver());

                var udpClient    = new UdpTransportClient(ipEndpoint);
                var udpTransport = new UdpTransport(udpClient, chunkConverter);
                return(udpTransport);
            }

            case SinkTransportType.Http:
            {
                var httpClient = new HttpTransportClient($"{_options.HostnameOrAddress}:{_options.Port}/gelf");

                var httpTransport = new HttpTransport(httpClient);
                return(httpTransport);
            }

            case SinkTransportType.Tcp:
            {
                var ipAddress = Task.Run(() => GetIpAddress(_options.HostnameOrAddress)).GetAwaiter().GetResult();
                var tcpClient = new TcpTransportClient(ipAddress, _options.Port);
                Task.Run(() => tcpClient.Connect()).GetAwaiter().GetResult();
                var transport = new TcpTransport(tcpClient);
                return(transport);
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(_options), _options.TransportType, null);
            }
        }
예제 #23
0
        public void Setup()
        {
            var config = new StatsDConfiguration
            {
                // if you want verify that stats are recevied,
                // you will need the IP of suitable local test stats server
                Host   = "127.0.0.1",
                Prefix = "testmetric"
            };

            var endpointSource = EndpointParser.MakeEndPointSource(
                config.Host, config.Port, config.DnsLookupInterval);

            var udpTransport = new UdpTransport(endpointSource);
            var ipTransport  = new IpTransport(endpointSource);

            _udpSender = new StatsDPublisher(config, udpTransport);
            _udpSender.Increment("startup.ud");

            _ipSender = new StatsDPublisher(config, ipTransport);
            _udpSender.Increment("startup.ip");
        }
예제 #24
0
        private static void ReceiverMode(ArgsParser parser)
        {
            if (parser
                .Keys("p", "port").Value <ushort>(out var port, 19000)
                .Keys("s", "jitter-size").Value(out var jitterSize, 120)
                .Keys("desired-latency").Value(out var desiredLatency, 60)
                .Keys("o", "output-device").Value(out var device, 0)
                .Result() != null)
            {
                return;
            }

            var jitterBufferAdapter = new JitterBufferAdapter(SAMPLE_RATE / MS_IN_SECOND * jitterSize);

            var rtpReceiver = new UdpTransport <IPacket>(new RtpContract(), port);

            rtpReceiver.Start();

            rtpReceiver.ReceivePacket += (sender, e) =>
            {
                if (e.Payload is RtpPacket packet)
                {
                    jitterBufferAdapter.Add(packet);
                }
            };

            var waveOut = new WaveOutEvent
            {
                DeviceNumber   = device,
                DesiredLatency = desiredLatency,
            };

            waveOut.Init(jitterBufferAdapter);
            waveOut.Play();

            Console.WriteLine("Press any key to stop");
            Console.ReadKey();
        }
예제 #25
0
 public void Check()
 {
     try
     {
         if (m_sock == null)
         {
             m_sock = new UdpTransport();
         }
         if (m_sock.IsOpened)
         {
             return;
         }
         if (!m_sock.IsOpened)
         {
             if (m_sock.Open(null, Settings.Setting.RcvPort, OnReceived, Settings.Setting.SendIP, Settings.Setting.SndPort))
             {
                 System.Diagnostics.Debug.WriteLine("udp check");
             }
         }
     }
     catch
     {
     }
 }
            public void ShouldSendShortUdpMessage()
            {
                var transportClient = new Mock <ITransportClient>();
                var transport       = new UdpTransport(transportClient.Object);
                var converter       = new Mock <IConverter>();
                var dnslookup       = new Mock <DnsBase>();

                converter.Setup(c => c.GetLogEventJson(It.IsAny <LogEventInfo>())).Returns(new JObject());

                var target = new NetworkJsonTarget(new [] { transport }, converter.Object, dnslookup.Object)
                {
                    Endpoint = "udp://127.0.0.1:12201"
                };
                var logEventInfo = new LogEventInfo {
                    Message = "Test Message"
                };

                dnslookup.Setup(x => x.GetHostAddresses(It.IsAny <string>())).Returns(new[] { IPAddress.Parse("127.0.0.1") });

                target.WriteLogEventInfo(logEventInfo);

                transportClient.Verify(t => t.Send(It.IsAny <byte[]>(), It.IsAny <Int32>(), It.IsAny <IPEndPoint>()), Times.Once());
                converter.Verify(c => c.GetLogEventJson(It.IsAny <LogEventInfo>()), Times.Once());
            }
예제 #27
0
        public void SendAndReceiveMultiple()
        {
            int           testerPort        = 45558;
            int           comServicePort    = 45556;
            string        testerAddress     = "127.0.0.1";
            string        comServiceAddress = "127.0.0.1";
            TestUdpSocket testerSocket      = new TestUdpSocket(testerPort);
            UdpTransport  testComService    = new UdpTransport();

            testComService.LocalEndpoint = new IPEndPoint(IPAddress.Any, comServicePort);

            testerSocket.Start();
            testComService.Start();
            AliveRequest request  = new AliveRequest();
            LoginRequest request2 = new LoginRequest();
            AliveReply   reply    = new AliveReply();


            int retries = 20;

            while (!(testerSocket.IsActive() && testComService.IsActive) && retries-- > 0 && wait(50))
            {
            }

            Assert.IsNotNull(testComService);
            Assert.IsTrue(testComService.IsActive);
            Assert.IsTrue(testerSocket.IsActive());

            testComService.Send(new Envelope(new IPEndPoint(IPAddress.Parse(testerAddress), testerPort), request));
            testComService.Send(new Envelope(new IPEndPoint(IPAddress.Parse(testerAddress), testerPort), reply));
            testComService.Send(new Envelope(new IPEndPoint(IPAddress.Parse(testerAddress), testerPort), request2));
            retries = 20;
            while (!testerSocket.ReplyWaiting && retries-- > 0 && wait(50))
            {
            }

            Assert.IsTrue(testerSocket.ReplyWaiting);
            Assert.IsTrue(testerSocket.Receive(out Envelope requestEnvelope));
            Assert.IsNotNull(requestEnvelope);
            Assert.IsTrue(requestEnvelope.Message.GetType() == request.GetType());
            Assert.IsTrue(requestEnvelope.Message.MsgId == request.MsgId);
            Assert.IsTrue(requestEnvelope.Message.ConvId == request.ConvId);
            Assert.IsTrue(requestEnvelope.Address.Address.ToString() == comServiceAddress);
            Assert.IsTrue(requestEnvelope.Address.Port == comServicePort);
            requestEnvelope = null;

            Assert.IsTrue(testerSocket.Receive(out requestEnvelope));
            Assert.IsNotNull(requestEnvelope);
            Assert.IsTrue(requestEnvelope.Message.GetType() == reply.GetType());
            Assert.IsTrue(requestEnvelope.Message.MsgId == reply.MsgId);
            Assert.IsTrue(requestEnvelope.Message.ConvId == reply.ConvId);
            Assert.IsTrue(requestEnvelope.Address.Address.ToString() == comServiceAddress);
            Assert.IsTrue(requestEnvelope.Address.Port == comServicePort);
            requestEnvelope = null;

            Assert.IsTrue(testerSocket.Receive(out requestEnvelope));
            Assert.IsNotNull(requestEnvelope);
            Assert.IsTrue(requestEnvelope.Message.GetType() == request2.GetType());
            Assert.IsTrue(requestEnvelope.Message.MsgId == request2.MsgId);
            Assert.IsTrue(requestEnvelope.Message.ConvId == request2.ConvId);
            Assert.IsTrue(requestEnvelope.Address.Address.ToString() == comServiceAddress);
            Assert.IsTrue(requestEnvelope.Address.Port == comServicePort);

            testerSocket.Send(new Envelope(new IPEndPoint(IPAddress.Parse(comServiceAddress), comServicePort), reply));

            retries = 20;
            while (!testComService.ReplyWaiting && retries-- > 0 && wait(50))
            {
            }

            Assert.IsTrue(testComService.ReplyWaiting);
            Assert.IsTrue(testComService.Receive(out Envelope replyEnvelope));
            Assert.IsNotNull(replyEnvelope);
            Assert.IsTrue(replyEnvelope.Message.GetType() == reply.GetType());
            Assert.IsTrue(replyEnvelope.Message.MsgId == reply.MsgId);
            Assert.IsTrue(replyEnvelope.Message.ConvId == reply.ConvId);
            Assert.IsTrue(replyEnvelope.Address.Address.ToString() == testerAddress);
            Assert.IsTrue(replyEnvelope.Address.Port == testerPort);
            testerSocket.Stop();
            testComService.Stop();

            retries = 20;
            while ((testerSocket.IsActive() || testComService.IsActive) && retries-- > 0 && wait(50))
            {
            }

            Assert.IsFalse(testComService.IsActive);
            Assert.IsFalse(testerSocket.IsActive());
        }
예제 #28
0
        private static void SenderMode(ArgsParser parser)
        {
            if (parser
                .Keys("r", "remote").Value(out var remote, new IPEndPoint(IPAddress.Loopback, 19000))
                .Keys("ssrc").Value(out var ssrc, 0x0000001u)
                .Keys("d", "packet-duration").Value(out var packetDuration, 60u)
                .Keys("i", "input-device").Value(out var device, 0)
                .Result() != null)
            {
                return;
            }

            var rnd       = new Random();
            var seqNumber = (ushort)rnd.Next();
            var timestamp = (uint)rnd.Next();
            var samples   = new short[SAMPLE_RATE / MS_IN_SECOND * packetDuration];
            var marker    = true;

            var codec     = new Opus();
            var rtpSender = new UdpTransport <IPacket>(new RtpContract(), 0);

            rtpSender.Start();

            var waveIn = new WaveInEvent
            {
                DeviceNumber       = device,
                WaveFormat         = new WaveFormat(SAMPLE_RATE, BIT_PER_SAMPLE, CHANNEL_COUNT),
                BufferMilliseconds = (int)packetDuration,
            };

            waveIn.DataAvailable += (sender, e) =>
            {
                var payload = new byte[e.BytesRecorded];
                Buffer.BlockCopy(e.Buffer, 0, samples, 0, e.BytesRecorded);
                Array.Resize(ref payload, codec.Encode(samples, 0, samples.Length, payload, 0, payload.Length));

                var packet = new RtpPacket
                {
                    Ssrc           = ssrc,
                    PayloadType    = PAYLOAD_TYPE_OPUS,
                    Marker         = marker,
                    Timestamp      = timestamp,
                    SequenceNumber = seqNumber,
                    Payload        = payload,
                };

                rtpSender.Send(new PacketContainer <IPacket>
                {
                    Target  = remote,
                    Payload = packet
                });

                timestamp += packetDuration;
                seqNumber += 1;
                marker     = false;
            };
            waveIn.StartRecording();

            Console.WriteLine("Press any key to stop");
            Console.ReadKey();
        }
예제 #29
0
 public Gateway(string sid, UdpTransport transport) : base(sid, "gateway")
 {
     _transport = transport;
 }
예제 #30
0
 public SocketPlug(string sid, UdpTransport transport) : base(sid, "plug")
 {
     _transport = transport;
 }