-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathNetworkInterface.cs
116 lines (98 loc) · 2.92 KB
/
NetworkInterface.cs
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
using System;
using System.Net;
using System.Net.Sockets;
using MQTT.Commands;
using System.Threading.Tasks;
using MQTT.Types;
using System.Threading;
namespace MQTT.Domain
{
public delegate void NetworkDisconnectedCallback(object sender, NetworkDisconenctedEventArgs e);
public class NetworkDisconenctedEventArgs : EventArgs
{
public NetworkDisconenctedEventArgs(NetworkConnection connection, Exception exception = null)
{
Connection = connection;
Exception = exception;
}
public NetworkConnection Connection { get; private set; }
public Exception Exception { get; private set; }
}
public sealed class NetworkInterface : INetworkInterface
{
Thread _recvThread;
readonly NetworkConnection _connection;
readonly ICommandReader _reader;
readonly ICommandWriter _writer;
public NetworkInterface(ICommandReader reader, ICommandWriter writer)
{
_connection = new NetworkConnection();
_reader = reader;
_writer = writer;
}
public void Disconnect()
{
_recvThread.Abort();
_connection.Disconnect();
}
public MqttCommand ReadCommand()
{
return _reader.Read(_connection);
}
public Task Send(MqttCommand command)
{
return _writer.Send(_connection, command);
}
public Task Connect(IPEndPoint endpoint)
{
return _connection.Connect(endpoint);
}
public void Start(Action<MqttCommand> onIncomingMessage)
{
_recvThread = new Thread(() => ReceiveLoop(onIncomingMessage));
_recvThread.Start();
}
public bool IsConnected
{
get
{
return _connection.Connected;
}
}
public void Dispose()
{
// do nothing
}
public event NetworkDisconnectedCallback OnNetworkDisconnected;
private void NotifyOfDisconnect(NetworkConnection connection, Exception ex)
{
NetworkDisconnectedCallback ev = OnNetworkDisconnected;
if (ev != null)
{
ev(this, new NetworkDisconenctedEventArgs(connection, ex));
}
}
private void ReceiveLoop(Action<MqttCommand> recv)
{
try
{
while (true)
{
MqttCommand command = ReadCommand();
if (recv != null)
{
recv(command);
}
}
}
catch (Exception ex)
{
if (_connection.Connected)
{
_connection.Disconnect();
}
NotifyOfDisconnect(_connection, ex);
}
}
}
}