Example #1
1
        } // End Sub Main 


        private static void UdpListener(int port)
        {
            System.Threading.Tasks.Task.Run(async () =>
            {
                using (var udpClient = new System.Net.Sockets.UdpClient(new System.Net.IPEndPoint(System.Net.IPAddress.Any, port)))
                {
                    while (true)
                    {
                        var receivedResults = await udpClient.ReceiveAsync();
                        var s = string.Format("[{0}] {1}", receivedResults.RemoteEndPoint, System.Text.Encoding.ASCII.GetString(receivedResults.Buffer));
                        System.Console.WriteLine(s);
                    }
                } // End Using

            }); // End Task.Run

        } // End Sub UdpListener
Example #2
0
        private static async Task Discover()
        {
            using (var server = new System.Net.Sockets.UdpClient(8888))
            {
                var responseData = System.Text.Encoding.ASCII.GetBytes($"port: {Port}|id: {ServerId:D}");

                while (!_stopping)
                {
                    try
                    {
                        var clientRequestData = await server.ReceiveAsync(); // (ref clientEp);

                        var clientRequest = System.Text.Encoding.ASCII.GetString(clientRequestData.Buffer);
                        if (clientRequest == "sync-service")
                        {
                            Console.WriteLine("Request from {0}, sending discover response", clientRequestData.RemoteEndPoint.Address);
                            await server.SendAsync(responseData, responseData.Length, clientRequestData.RemoteEndPoint);
                        }
                        else
                        {
                            Console.WriteLine("Request from {0} invalid {1}", clientRequestData.RemoteEndPoint.Address, clientRequest);
                            await server.SendAsync(responseData, responseData.Length, clientRequestData.RemoteEndPoint);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Failed on discovery: {e}");
                        await Task.Delay(2000);
                    }
                }
            }
        }
Example #3
0
        public Task <byte[]> ReceiveAsync()
        {
            var recvTask = _udpClient.ReceiveAsync();

            recvTask.Wait(_cancelListenerSource.Token);

            _cancelListenerSource.Token.ThrowIfCancellationRequested();
            return(Task.FromResult(recvTask.Result.Buffer));
        }
Example #4
0
        private static void Main(string[] args)
        {
            byte[] toDisplay = null;

            var consoleUpdater = Task.Run(async() =>
            {
                while (true)
                {
                    if (toDisplay != null)
                    {
                        Console.SetCursorPosition(0, 0);
                        Console.Write(StatusScreen(toDisplay));
                        toDisplay = null;
                    }

                    await Task.Delay(300);
                }
            });


            var ipEndPoint   = new IPEndPoint(IPAddress.Loopback, FORZA_DATA_OUT_PORT);
            var senderClient = new System.Net.Sockets.UdpClient(FORZA_HOST_PORT);
            var senderTask   = Task.Run(async() =>
            {
                while (true)
                {
                    Console.WriteLine("Sending heartbeat");
                    await senderClient.SendAsync(new byte[1], 1, ipEndPoint);
                    await Task.Delay(5000);
                }
            });

            var receiverTask = Task.Run(async() =>
            {
                Console.Clear();
                var client = new System.Net.Sockets.UdpClient(FORZA_DATA_OUT_PORT);
                Console.WriteLine("Listening... ");
                while (true)
                {
                    await client.ReceiveAsync().ContinueWith(receive =>
                    {
                        var resultBuffer = receive.Result.Buffer;
                        if (resultBuffer.Length != 311 || toDisplay != null)
                        {
                            return;
                        }

                        var stuff = new byte[resultBuffer.Length];
                        resultBuffer.CopyTo(stuff, 0);
                        toDisplay = stuff;
                    });
                }
            });


            Task.WaitAll(senderTask, receiverTask, consoleUpdater);
        }
Example #5
0
        public async Task <RecievedData> Receive()
        {
            var result = await Client.ReceiveAsync();

            return(new RecievedData()
            {
                Datagram = result.Buffer,
                EndPoint = result.RemoteEndPoint
            });
        }
Example #6
0
        public ReplyData GetReply(InputData data)
        {
            byte[] inputBuffer = ByteArray.CreateFrom(data);
            server.SendAsync(inputBuffer, inputBuffer.Length, destination).Wait();

            var message   = replySocket.ReceiveAsync().Result.Buffer;
            var replyData = message.ConvertTo <ReplyData>();

            return(replyData);
        }
Example #7
0
        public async Task <Received> Receive()
        {
            var result = await Client.ReceiveAsync();

            return(new Received
            {
                Message = Encoding.ASCII.GetString(result.Buffer, 0, result.Buffer.Length),
                Sender = result.RemoteEndPoint
            });
        }
Example #8
0
        public async Task <Received> Receive()
        {
            var result = await client.ReceiveAsync();

            _connections.Add(result.RemoteEndPoint);
            return(new Received
            {
                Message = Encoding.UTF8.GetString(result.Buffer, 0, result.Buffer.Length),
                Sender = result.RemoteEndPoint
            });
        }
Example #9
0
        } // End Sub Main

        private static void UdpListener(int port)
        {
            System.Threading.Tasks.Task.Run(async() =>
            {
                using (var udpClient = new System.Net.Sockets.UdpClient(new System.Net.IPEndPoint(System.Net.IPAddress.Any, port)))
                {
                    while (true)
                    {
                        var receivedResults = await udpClient.ReceiveAsync();
                        var s = string.Format("[{0}] {1}", receivedResults.RemoteEndPoint, System.Text.Encoding.ASCII.GetString(receivedResults.Buffer));
                        System.Console.WriteLine(s);
                    }
                } // End Using
            }); // End Task.Run
        }         // End Sub UdpListener
Example #10
0
        private async Task RunAsync(CancellationToken cancelToken)
        {
            var closeTask = Task.Delay(-1, cancelToken);

            while (!cancelToken.IsCancellationRequested)
            {
                var receiveTask = _udp.ReceiveAsync();
                var task        = await Task.WhenAny(closeTask, receiveTask).ConfigureAwait(false);

                if (task == closeTask)
                {
                    break;
                }

                var result = receiveTask.Result;
                await ReceivedDatagram(result.Buffer, 0, result.Buffer.Length).ConfigureAwait(false);
            }
        }
Example #11
0
        private async Task RunLoop(CancellationToken cancellationToken)
        {
            var number = 1;

            while (!cancellationToken.IsCancellationRequested)
            {
                Debug.WriteLine($"{number}: Starting Listening");
                var message = await sysClient.ReceiveAsync();

                var x = number;
                _ = Task.Run(() => {
                    Debug.WriteLine($"{x}: Received {string.Join(' ', message.Buffer.Select(x => x.ToString()))}");
                    foreach (var observer in observers.Keys)
                    {
                        observer.OnNext(message.Buffer);
                    }
                });
                number++;
            }
        }
Example #12
0
        override protected async void Run()
        {
            //var sock = new Sockets.Plugin.UdpSocketReceiver();
            var sock = new System.Net.Sockets.UdpClient(
                new System.Net.IPEndPoint(System.Net.IPAddress.Any, myPort));

            sock.EnableBroadcast = true;

            using (sock.Client) //make sure the socket gets cleaned up on exit
                using (decoder)
                {
                    //config the decoder with the info/meta data from the stream
                    decoder.Configure(format, surface, null, MediaCodecConfigFlags.None);
                    decoder.Start();

                    bool isEOS    = false;
                    bool foundNAL = false;
                    int  count    = 0;

                    while (running)
                    {
                        ++count;
                        try
                        {
                            while (buffEx.SampleCount == 0 && running)
                            {
                                //we need a new buffer every loop!
                                //buff = new byte[188];
                                var pack = await sock.ReceiveAsync().ConfigureAwait(false);

                                //we may need to check the source here too? or specify above.
                                //if (pack.Buffer.Length != TsPacket.PacketLength )
                                //    continue;//wait for next packet, not a TS packet

                                //could check # of non-TS packets and abort if too many?

                                //push the raw data to our custom extractor
                                if (!buffEx.AddRaw(pack.Buffer))
                                {
                                    Log.Debug("ExtractorActivity,   ", " ----------bad TS packet!");
                                }
                            }

                            if (!running)
                            {
                                break;//exit the render loop
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error("ExtractorActivity error: ", ex.ToString());
                        }

                        var sample = buffEx.DequeueNextSample();
                        Log.Debug("ExtractorActivity, sampleSize: ", sample.Length.ToString());

                        //get a input buffer index from the decoder for input
                        int inIndex = decoder.DequeueInputBuffer(10000);


                        if (inIndex >= 0)
                        {
                            //get the re-assembled video data from the extractor
                            using (var b = Java.Nio.ByteBuffer.Wrap(sample.Buffer))
                            {
                                var inB = inputBuffers[inIndex];
                                //*************
                                //THE BUFFER *******MUST********* be CLEARED before each write,
                                //else when the buffers start getting recycled, the decoder will
                                //read past the end of the current data into old data!
                                //This may cause tearing of the picture, or even a complete
                                //crash of the app from internal errors in native decoder code!!!!!
                                inB.Clear();
                                inB.Put(b);//put data into the decoder's native buffer

                                //tell the decoder about the new data in the buffer
                                decoder.QueueInputBuffer(inIndex, 0, b.Limit(), 0, MediaCodecBufferFlags.None);
                            }//  b.Dispose();//clean up
                        }


                        int outIndex = decoder.DequeueOutputBuffer(info, 10000);
                        switch ((Android.Media.MediaCodecInfoState)outIndex)
                        {
                        case MediaCodecInfoState.OutputBuffersChanged:
                            Android.Util.Log.Debug("DecodeActivity",
                                                   MediaCodecInfoState.OutputBuffersChanged.ToString());
                            outputBuffers = decoder.GetOutputBuffers();
                            break;

                        case MediaCodecInfoState.OutputFormatChanged:

                            Android.Util.Log.Debug("DecodeActivity", "New format " + decoder.OutputFormat);//.GetOutputFormat(outIndex));
                            break;

                        case MediaCodecInfoState.TryAgainLater:
                            Android.Util.Log.Debug("DecodeActivity", "dequeueOutputBuffer timed out!");
                            break;

                        default:
                            //must pull off old buffers to keep things going...
                            var buffer = outputBuffers[outIndex];
                            Android.Util.Log.Verbose("DecodeActivity", "We can't use this buffer but render it due to the API limit, " + buffer);

                            //no clock needed for live streaming?
                            //// We use a very simple clock to keep the video FPS, or the video
                            //// playback will be too fast
                            //while (info.PresentationTimeUs / 1000 > sw.ElapsedMilliseconds)
                            //{
                            //    try
                            //    {
                            //        await Task.Delay(10).ConfigureAwait(false);
                            //        //sleep(10);
                            //    }
                            //    catch (Exception e)
                            //    {
                            //        //e.printStackTrace();
                            //        System.Diagnostics.Debug.WriteLine(e.StackTrace);
                            //        break;
                            //    }
                            //}
                            decoder.ReleaseOutputBuffer(outIndex, true);
                            break;
                        }

                        // All decoded frames have been rendered, we can stop playing now
                        if ((info.Flags & MediaCodecBufferFlags.EndOfStream) != 0)
                        {
                            Android.Util.Log.Debug("DecodeActivity",
                                                   MediaCodecBufferFlags.EndOfStream.ToString());
                            break;
                        }
                    }
                }

            info    = null;
            decoder = null;
        }
Example #13
0
        override protected async void Run()
        {
            //var sock = new Sockets.Plugin.UdpSocketReceiver();
            var sock = new System.Net.Sockets.UdpClient(
                            new System.Net.IPEndPoint(System.Net.IPAddress.Any, myPort));
            sock.EnableBroadcast = true;

            using (sock.Client)//make sure the socket gets cleaned up on exit
            using (decoder)
            {
                //config the decoder with the info/meta data from the stream
                decoder.Configure(format, surface, null, MediaCodecConfigFlags.None);
                decoder.Start();

                bool isEOS = false;
                bool foundNAL = false;
                int count = 0;

                while (running)
                {
                    ++count;
                    try
                    {
                        while (buffEx.SampleCount == 0 && running)
                        {
                            //we need a new buffer every loop!
                            //buff = new byte[188];
                            var pack = await sock.ReceiveAsync().ConfigureAwait(false);

                            //we may need to check the source here too? or specify above.
                            //if (pack.Buffer.Length != TsPacket.PacketLength )
                            //    continue;//wait for next packet, not a TS packet

                            //could check # of non-TS packets and abort if too many?

                            //push the raw data to our custom extractor
                            if (!buffEx.AddRaw(pack.Buffer))
                            {
                                Log.Debug("ExtractorActivity,   ", " ----------bad TS packet!");

                            }
                        }

                        if (!running)
                            break;//exit the render loop
                    }
                    catch (Exception ex)
                    {
                        Log.Error("ExtractorActivity error: ", ex.ToString());
                    }

                    var sample = buffEx.DequeueNextSample();
                    Log.Debug("ExtractorActivity, sampleSize: ", sample.Length.ToString());

                    //get a input buffer index from the decoder for input
                    int inIndex = decoder.DequeueInputBuffer(10000);


                    if (inIndex >= 0)
                    {
                        //get the re-assembled video data from the extractor
                        using (var b = Java.Nio.ByteBuffer.Wrap(sample.Buffer))
                        {

                            var inB = inputBuffers[inIndex];
                            //*************
                            //THE BUFFER *******MUST********* be CLEARED before each write,
                            //else when the buffers start getting recycled, the decoder will
                            //read past the end of the current data into old data!
                            //This may cause tearing of the picture, or even a complete 
                            //crash of the app from internal errors in native decoder code!!!!!
                            inB.Clear();
                            inB.Put(b);//put data into the decoder's native buffer

                            //tell the decoder about the new data in the buffer
                            decoder.QueueInputBuffer(inIndex, 0, b.Limit(), 0, MediaCodecBufferFlags.None);

                        }//  b.Dispose();//clean up
                    }


                    int outIndex = decoder.DequeueOutputBuffer(info, 10000);
                    switch ((Android.Media.MediaCodecInfoState)outIndex)
                    {
                        case MediaCodecInfoState.OutputBuffersChanged:
                            Android.Util.Log.Debug("DecodeActivity",
                                                    MediaCodecInfoState.OutputBuffersChanged.ToString());
                            outputBuffers = decoder.GetOutputBuffers();
                            break;
                        case MediaCodecInfoState.OutputFormatChanged:

                            Android.Util.Log.Debug("DecodeActivity", "New format " + decoder.OutputFormat);//.GetOutputFormat(outIndex));
                            break;
                        case MediaCodecInfoState.TryAgainLater:
                            Android.Util.Log.Debug("DecodeActivity", "dequeueOutputBuffer timed out!");
                            break;
                        default:
                            //must pull off old buffers to keep things going...
                            var buffer = outputBuffers[outIndex];
                            Android.Util.Log.Verbose("DecodeActivity", "We can't use this buffer but render it due to the API limit, " + buffer);

                    //no clock needed for live streaming?
                            //// We use a very simple clock to keep the video FPS, or the video
                            //// playback will be too fast
                            //while (info.PresentationTimeUs / 1000 > sw.ElapsedMilliseconds)
                            //{
                            //    try
                            //    {
                            //        await Task.Delay(10).ConfigureAwait(false);
                            //        //sleep(10);
                            //    }
                            //    catch (Exception e)
                            //    {
                            //        //e.printStackTrace();
                            //        System.Diagnostics.Debug.WriteLine(e.StackTrace);
                            //        break;
                            //    }
                            //}
                            decoder.ReleaseOutputBuffer(outIndex, true);
                            break;
                    }

                    // All decoded frames have been rendered, we can stop playing now
                    if ((info.Flags & MediaCodecBufferFlags.EndOfStream) != 0)
                    {
                        Android.Util.Log.Debug("DecodeActivity",
                                                MediaCodecBufferFlags.EndOfStream.ToString());
                        break;
                    }
                }
            }

            info = null;
            decoder = null;
        }