summaryrefslogtreecommitdiff
path: root/Impostor-dev/src/Impostor.Hazel/Udp/UdpBroadcaster.cs
blob: 5fa1ccac255ac37351a12e52ec9d9abfb428132a (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
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Impostor.Hazel.Udp
{
    ///
    public class UdpBroadcaster : IDisposable
    {
        private Socket socket;
        private byte[] data;
        private EndPoint endpoint;
        private Action<string> logger;

        ///
        public UdpBroadcaster(int port, Action<string> logger = null)
        {
            this.logger = logger;
            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            this.socket.EnableBroadcast = true;
            this.socket.MulticastLoopback = false;
            this.endpoint = new IPEndPoint(IPAddress.Broadcast, port);
        }

        ///
        public void SetData(string data)
        {
            int len = UTF8Encoding.UTF8.GetByteCount(data);
            this.data = new byte[len + 2];
            this.data[0] = 4;
            this.data[1] = 2;

            UTF8Encoding.UTF8.GetBytes(data, 0, data.Length, this.data, 2);
        }

        ///
        public void Broadcast()
        {
            if (this.data == null)
            {
                return;
            }

            try
            {
                this.socket.BeginSendTo(data, 0, data.Length, SocketFlags.None, this.endpoint, this.FinishSendTo, null);
            }
            catch (Exception e)
            {
                this.logger?.Invoke("BroadcastListener: " + e);
            }
        }

        private void FinishSendTo(IAsyncResult evt)
        {
            try
            {
                this.socket.EndSendTo(evt);
            }
            catch (Exception e)
            {
                this.logger?.Invoke("BroadcastListener: " + e);
            }
        }

        ///
        public void Dispose()
        {
            if (this.socket != null)
            {
                try { this.socket.Shutdown(SocketShutdown.Both); } catch { }
                try { this.socket.Close(); } catch { }
                try { this.socket.Dispose(); } catch { }
                this.socket = null;
            }
        }
    }
}