Example #1
0
        /// <summary>
        /// Receive data from the group and log it.
        /// </summary>
        private void Receive()
        {
            // Only attempt to receive if you have already joined the group
            if (_joined)
            {
                Array.Clear(_receiveBuffer, 0, _receiveBuffer.Length);
                _client.BeginReceiveFromGroup(_receiveBuffer, 0, _receiveBuffer.Length,
                                              result =>
                {
                    IPEndPoint source;

                    // Complete the asynchronous operation. The source field will
                    // contain the IP address of the device that sent the message
                    _client.EndReceiveFromGroup(result, out source);

                    if (OnClientFound != null && _receiveBuffer[0] == 1)
                    {
                        byte[] temp = new byte[4];
                        Array.Copy(_receiveBuffer, 1, temp, 0, 4);
                        OnClientFound(temp);
                    }

                    // Call receive again to continue to "listen" for the next message from the group
                    Receive();
                }, null);
            }
            else
            {
                //Log("Cannot receive. You are currently not joined to the group", true);
            }
        }
Example #2
0
        public Task <ReceivedUdpData> ReceiveAsync()
        {
            ThrowIfDisposed();

            var taskCompletionSource = new System.Threading.Tasks.TaskCompletionSource <ReceivedUdpData>();

            byte[] buffer = new byte[SsdpConstants.DefaultUdpSocketBufferSize];
            _UdpClient.BeginReceiveFromGroup(buffer, 0, buffer.Length,
                                             (asyncResult) =>
            {
                IPEndPoint receivedFromEndPoint;

                _UdpClient.EndReceiveFromGroup(asyncResult, out receivedFromEndPoint);

                var tcs = asyncResult.AsyncState as System.Threading.Tasks.TaskCompletionSource <ReceivedUdpData>;

                var result = new ReceivedUdpData()
                {
                    ReceivedFrom = new UdpEndPoint()
                    {
                        IPAddress = receivedFromEndPoint.Address.ToString(),
                        Port      = receivedFromEndPoint.Port
                    },
                    Buffer        = buffer,
                    ReceivedBytes = buffer.Length
                };

                tcs.SetResult(result);
            },
                                             taskCompletionSource
                                             );

            return(taskCompletionSource.Task);
        }
Example #3
0
        private async void StartReceiving()
        {
            CancellationToken token = this.receiverCts.Token;

            while (!token.IsCancellationRequested)
            {
                try
                {
                    byte[] receivedData  = new byte[4096];
                    var    receiveResult = await Task.Factory.FromAsync(
                        client.BeginReceiveFromGroup,
                        (iar) =>
                    {
                        IPEndPoint endpoint;
                        int result = client.EndReceiveFromGroup(iar, out endpoint);

                        return(Tuple.Create(result, endpoint));
                    },
                        receivedData,
                        0,
                        receivedData.Length, null, TaskCreationOptions.None);

                    DecodeMessage(receivedData, receiveResult.Item2);
                }
                catch (Exception)
                {
                }
            }
        }
Example #4
0
        public Task <ReceivedUdpData> ReceiveAsync()
        {
            ThrowIfDisposed();

            var taskCompletionSource = new System.Threading.Tasks.TaskCompletionSource <ReceivedUdpData>();

            byte[] buffer = new byte[SsdpConstants.DefaultUdpSocketBufferSize];
            try
            {
                _UdpClient.BeginReceiveFromGroup(buffer, 0, buffer.Length,
                                                 (asyncResult) =>
                {
                    IPEndPoint receivedFromEndPoint;

                    try
                    {
                        _UdpClient.EndReceiveFromGroup(asyncResult, out receivedFromEndPoint);

                        var tcs = asyncResult.AsyncState as System.Threading.Tasks.TaskCompletionSource <ReceivedUdpData>;

                        var result = new ReceivedUdpData()
                        {
                            ReceivedFrom = new UdpEndPoint()
                            {
                                IPAddress = receivedFromEndPoint.Address.ToString(),
                                Port      = receivedFromEndPoint.Port
                            },
                            Buffer        = buffer,
                            ReceivedBytes = buffer.Length
                        };

                        tcs.SetResult(result);
                    }
                    catch (SocketException se)
                    {
                        if (se.SocketErrorCode == SocketError.Shutdown || se.SocketErrorCode == SocketError.OperationAborted || se.SocketErrorCode == SocketError.NotConnected)
                        {
                            throw new SocketClosedException(se.Message, se);
                        }

                        throw;
                    }
                },
                                                 taskCompletionSource
                                                 );
            }
            catch (SocketException se)
            {
                if (se.SocketErrorCode == SocketError.Shutdown || se.SocketErrorCode == SocketError.OperationAborted || se.SocketErrorCode == SocketError.NotConnected)
                {
                    throw new SocketClosedException(se.Message, se);
                }

                throw;
            }

            return(taskCompletionSource.Task);
        }
        private void Receive()
        {
            // Only attempt to receive if you have already joined the group
            if (_joined)
            {
                Array.Clear(_receiveBuffer, 0, _receiveBuffer.Length);
                _client.BeginReceiveFromGroup(_receiveBuffer, 0, _receiveBuffer.Length,
                                              result =>
                {
                    IPEndPoint source;

                    // Complete the asynchronous operation. The source field will
                    // contain the IP address of the device that sent the message
                    _client.EndReceiveFromGroup(result, out source);

                    // Get the received data from the buffer.
                    string dataReceived = Encoding.UTF8.GetString(_receiveBuffer, 0, _receiveBuffer.Length);
                    string[] msg        = dataReceived.Split(',');

                    double latitude;
                    double longitude;
                    //double heading;

                    try
                    {
                        if (Double.TryParse(msg[0], out latitude))
                        {
                            current.Latitude = latitude;
                        }
                        if (Double.TryParse(msg[1], out longitude))
                        {
                            current.Longitude = longitude;
                        }
                        //if (Double.TryParse(msg[2], out heading))
                        //current.Course = heading;
                    }
                    catch { }
                    // Create a log entry.
                    //string message = String.Format("[{0}]: {1}", source.Address.ToString(), dataReceived);

                    // Log it.
                    Log(dataReceived, "sub");

                    // Call receive again to continue to "listen" for the next message from the group
                    Receive();
                }, null);
            }
            else
            {
                MessageBox.Show("Cant receive - not connected to Multicast group");
            }
        }
Example #6
0
        void DoneReceiveFromGroup(IAsyncResult result)
        {
            IPEndPoint where;
            int responselength = MulticastSocket.EndReceiveFromGroup(result, out where);

            byte[] buffer = result.AsyncState as byte[];
            if (responselength == MulticastData.Length && buffer.SequenceEqual(MulticastData))
            {
                Debug.WriteLine("FOUND myself at " + where.Address.ToString());
                keepsearching = false;
                FoundCallback(where.Address);
            }
        }
Example #7
0
        private void StartReceiving(IAsyncResult result)
        {
            //result.AsyncWaitHandle.WaitOne();
            IPEndPoint src = new IPEndPoint(IPAddress.Any, 0);

            try
            {
                client.EndReceiveFromGroup(result, out src);
                Treat(mReceived, src);
            }
            catch (WebException)
            {
            }
        }
Example #8
0
        public static Task <UdpAnySourceMulticastClientReceieveFromGroupResult> ReceiveFromGroupAsync(this UdpAnySourceMulticastClient client, byte[] buffer, int offset, int count)
        {
            var taskCompletionSource = new TaskCompletionSource <UdpAnySourceMulticastClientReceieveFromGroupResult>();

            client.BeginReceiveFromGroup(buffer, offset, count, asyncResult =>
            {
                try
                {
                    IPEndPoint source;
                    int length = client.EndReceiveFromGroup(asyncResult, out source);
                    taskCompletionSource.TrySetResult(new UdpAnySourceMulticastClientReceieveFromGroupResult(length, source));
                }
                catch (Exception ex)
                {
                    taskCompletionSource.TrySetException(ex);
                }
            }, null);

            return(taskCompletionSource.Task);
        }
Example #9
0
        private static void Receive()
        {
            // Only attempt to receive if you have already joined the group
            if (_joined)
            {
                Array.Clear(_receiveBuffer, 0, _receiveBuffer.Length);
                _client.BeginReceiveFromGroup(_receiveBuffer, 0, _receiveBuffer.Length,
                                              result =>
                {
                    IPEndPoint source;

                    // Complete the asynchronous operation. The source field will
                    // contain the IP address of the device that sent the message
                    _client.EndReceiveFromGroup(result, out source);


                    OnReceivedData(_receiveBuffer);

                    // Call receive again to continue to "listen" for the next message from the group
                    Receive();
                }, null);
            }
        }
        private void Receive()
        {
            myClient.BeginReceiveFromGroup(receiveBuffer, 0, receiveBuffer.Length,
                                           result =>
            {
                try {
                    IPEndPoint source;
                    myClient.EndReceiveFromGroup(result, out source);
                    string sourceIPAddress = source.Address.ToString();

                    Dispatcher.BeginInvoke(() =>
                    {
                        count++;
                        textBlock1.Text = count.ToString();

                        //var b = new WriteableBitmap( width, height );
                        //for ( int i = 0; i < b.Pixels.Length; i++ ) {
                        //    int index = i * 4;
                        //    b.Pixels[i] = receiveBuffer[index + 0] << 24 |
                        //                  receiveBuffer[index + 1] << 16 |
                        //                  receiveBuffer[index + 2] << 8 |
                        //                  receiveBuffer[index + 3];
                        //}
                        //image1.Source = b;

                        var b = new WriteableBitmap(width, height);

                        for (int i = 0; i < skeleton.Length; i++)
                        {
                            int index   = i * 4;
                            skeleton[i] = receiveBuffer[index + 3] << 24 |
                                          receiveBuffer[index + 2] << 16 |
                                          receiveBuffer[index + 1] << 8 |
                                          receiveBuffer[index + 0];
                        }

                        canvas1.Children.Clear();
                        for (int i = 0; i < skeleton.Length; i += 2)
                        {
                            int x = i;
                            int y = i + 1;

                            //b.Pixels[y * width + x] = 0xFFFFFFF;
                            var e = new Ellipse()
                            {
                                Fill = new SolidColorBrush()
                                {
                                    Color = Colors.Red
                                },
                                Width  = 10,
                                Height = 10,
                            };

                            Canvas.SetLeft(e, skeleton[x]);
                            Canvas.SetTop(e, skeleton[y]);
                            canvas1.Children.Add(e);
                        }
                    });

                    Receive();
                }
                catch (Exception ex) {
                    Receive();

                    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("recv error " + ex.Message);
                    });
                }
            },
                                           null
                                           );
        }