aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Transport/Discovery/UdpDiscoveryClient.cs
blob: 773ba288afc3cd65621e36c40a464d7b7d4a4cda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Tango.PMR.Discovery;

namespace Tango.Transport.Discovery
{
    public class UdpDiscoveryClient<DiscoveryMessage> : IDiscoveryClient<DiscoveryMessage> where DiscoveryMessage : IMessage
    {
        private Thread _receiveThread;

        /// <summary>
        /// Occurs when a matching service has been discovered.
        /// </summary>
        public event EventHandler<DiscoveredService<DiscoveryMessage>> ServiceDiscovered;

        /// <summary>
        /// Gets or sets the interval in which the discovery message will be sent.
        /// </summary>
        public TimeSpan Interval { get; set; }

        /// <summary>
        /// Gets a value indicating whether this service has been started.
        /// </summary>
        public bool IsStarted { get; private set; }

        /// <summary>
        /// Gets the UDP port number.
        /// </summary>
        public int Port { get; private set; }

        /// <summary>
        /// Prevents a default instance of the <see cref="UdpDiscoveryClient"/> class from being created.
        /// </summary>
        private UdpDiscoveryClient()
        {
            Interval = TimeSpan.FromSeconds(5);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="UdpDiscoveryClient"/> class.
        /// </summary>
        /// <param name="port">The UDP port number.</param>
        public UdpDiscoveryClient(int port) : this()
        {
            Port = port;
        }

        /// <summary>
        /// Starts the discovery client.
        /// </summary>
        public void Start()
        {
            if (!IsStarted)
            {
                IsStarted = true;

                _receiveThread = new Thread(ReceiveThreadLoop);
                _receiveThread.IsBackground = true;
                _receiveThread.Start();
            }
        }

        /// <summary>
        /// Stops the discovery client.
        /// </summary>
        public void Stop()
        {
            if (IsStarted)
            {
                IsStarted = false;
            }
        }

        /// <summary>
        /// Handles the Elapsed event of the _timer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="ElapsedEventArgs"/> instance containing the event data.</param>
        private void ReceiveThreadLoop()
        {
            UdpClient udpClient = new UdpClient(Port);
            udpClient.Client.ReceiveTimeout = (int)Interval.TotalMilliseconds;
            var endPoint = new IPEndPoint(IPAddress.Any, Port);

            while (IsStarted)
            {
                try
                {
                    byte[] data = null;

                    do
                    {
                        data = udpClient.Receive(ref endPoint);

                        if (IsStarted)
                        {
                            if (data != null && data.Length > 0)
                            {
                                DiscoveryMessage message = Activator.CreateInstance<DiscoveryMessage>();
                                var parser = message.GetParser();

                                message = (DiscoveryMessage)parser.ParseFrom(data);

                                var host = Dns.GetHostEntry(endPoint.Address);
                                string address = endPoint.Address.ToString();

                                ServiceDiscovered?.Invoke(this,
                                    new DiscoveredService<DiscoveryMessage>(
                                        address,
                                        host != null ? host.HostName : "Unresolved",
                                        message
                                        , () =>
                                         {

                                             try
                                             {
                                                 TcpClient client = new TcpClient();
                                                 client.Connect(address, Port);
                                                 client.Dispose();
                                                 return true;
                                             }
                                             catch
                                             {
                                                 return false;
                                             }

                                         }));
                            }
                        }

                    } while (IsStarted && data != null && data.Length > 0);
                }
                catch { }

                if (!IsStarted) break;

                Thread.Sleep(Interval);
            }

            udpClient.Close();
        }

        /// <summary>
        /// Asynchronous method for awaiting until the service will be discovered.
        /// </summary>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public Task<DiscoveredService<DiscoveryMessage>> Discover(TimeSpan? timeout = null)
        {
            Start();

            TaskCompletionSource<DiscoveredService<DiscoveryMessage>> source = new TaskCompletionSource<DiscoveredService<DiscoveryMessage>>();

            EventHandler<DiscoveredService<DiscoveryMessage>> handler = null;

            handler = (sender, e) =>
            {
                ServiceDiscovered -= handler;
                source.SetResult(e);
            };

            ServiceDiscovered += handler;

            Task.Delay(timeout != null ? timeout.Value : TimeSpan.FromSeconds(10)).ContinueWith((x) =>
            {
                if (!source.Task.IsCompleted)
                {
                    source.SetException(new TimeoutException());
                }
            });

            return source.Task;
        }
    }
}