-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetClient.cs
247 lines (211 loc) · 5.96 KB
/
NetClient.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
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using static SylverInk.Common;
using static SylverInk.Network;
namespace SylverInk
{
public partial class NetClient
{
public bool Active { get; set; } = false;
public IPAddress? Address { get; set; }
public string? AddressCode { get; set; }
private BackgroundWorker ClientTask { get; set; } = new() { WorkerSupportsCancellation = true };
public bool Connected { get; private set; } = false;
public bool Connecting { get; private set; } = false;
public Database? DB { get; set; }
private TcpClient DBClient { get; set; } = new();
public byte? Flags;
public System.Windows.Shapes.Ellipse? Indicator { get; set; }
public NetClient(Database DB)
{
this.DB = DB;
Indicator = new() { StrokeThickness = 1.0 };
ClientTask.DoWork += (sender, _) =>
{
var task = (BackgroundWorker?)sender;
while (!task?.CancellationPending is true)
{
try
{
if (DBClient.Available > 0)
Concurrent(ReadFromStream);
if (!DBClient.Connected || !DBClient.GetStream().Socket.Connected)
Concurrent(Disconnect);
}
catch
{
Concurrent(Disconnect);
}
}
};
}
public async Task Connect(string code)
{
if (code.Length != 6)
return;
Active = true;
Address = CodeToAddress(code, out Flags);
AddressCode = CodeFromAddress(Address, Flags);
if (DBClient.Connected)
Disconnect();
Connecting = true;
UpdateIndicator();
DBClient = new()
{
ReceiveBufferSize = int.MaxValue,
SendBufferSize = int.MaxValue
};
try
{
await DBClient.ConnectAsync(Address, TcpPort);
await DBClient.GetStream().WriteAsync(new List<byte>([Flags ?? 0]).ToArray());
}
catch
{
MessageBox.Show("Failed to connect to the database.", "Sylver Ink: Error", MessageBoxButton.OK, MessageBoxImage.Error);
if (DB is not null)
Concurrent(() => RemoveDatabase(DB));
return;
}
ClientTask.RunWorkerAsync();
}
public async void Disconnect()
{
ClientTask.CancelAsync();
DBClient?.Close();
await Task.Run(() => SpinWait.SpinUntil(new(() => !DBClient?.Connected is true)));
DBClient?.Dispose();
Active = false;
Connected = false;
UpdateIndicator();
}
private void ReadFromStream()
{
int oldData = DBClient.Available;
bool dataFinished = false;
do
{
dataFinished = !SpinWait.SpinUntil(new(() => DBClient.Available != oldData), 500);
oldData = DBClient.Available;
} while (!dataFinished);
var stream = DBClient.GetStream();
var type = (MessageType)stream.ReadByte();
var intBuffer = new byte[4];
var recordIndex = 0;
byte[] textBuffer;
var textCount = 0;
stream.Read(intBuffer, 0, 4);
recordIndex = IntFromBytes(intBuffer);
switch (type)
{
case MessageType.DatabaseInit:
stream.Read(intBuffer, 0, 4);
textCount = IntFromBytes(intBuffer);
if (textCount > 0)
{
textBuffer = new byte[textCount];
stream.Read(textBuffer, 0, textCount);
DB?.DeserializeRecords(new(textBuffer));
Connecting = false;
Connected = true;
UpdateIndicator();
DB?.GetHeader();
Concurrent(() => DeferUpdateRecentNotes(true));
}
break;
case MessageType.RecordAdd:
stream.Read(intBuffer, 0, 4);
textCount = IntFromBytes(intBuffer);
if (textCount > 0)
{
textBuffer = new byte[textCount];
stream.Read(textBuffer, 0, textCount);
DB?.CreateRecord(Encoding.UTF8.GetString(textBuffer), false);
Concurrent(() => DeferUpdateRecentNotes());
break;
}
DB?.CreateRecord(string.Empty, false);
Concurrent(() => DeferUpdateRecentNotes());
break;
case MessageType.RecordLock:
DB?.Lock(recordIndex);
break;
case MessageType.RecordRemove:
DB?.DeleteRecord(recordIndex, false);
Concurrent(() => DeferUpdateRecentNotes());
break;
case MessageType.RecordReplace:
stream.Read(intBuffer, 0, 4);
textCount = IntFromBytes(intBuffer);
if (textCount > 0)
{
textBuffer = new byte[textCount];
stream.Read(textBuffer, 0, textCount);
var oldText = Encoding.UTF8.GetString(textBuffer);
stream.Read(intBuffer, 0, 4);
textCount = IntFromBytes(intBuffer);
if (textCount > 0)
{
textBuffer = new byte[textCount];
stream.Read(textBuffer, 0, textCount);
var newText = Encoding.UTF8.GetString(textBuffer);
DB?.Replace(oldText, newText, false);
Concurrent(() => DeferUpdateRecentNotes());
}
}
break;
case MessageType.RecordUnlock:
DB?.Unlock(recordIndex);
break;
case MessageType.TextInsert:
stream.Read(intBuffer, 0, 4);
textCount = IntFromBytes(intBuffer);
if (textCount > 0)
{
textBuffer = new byte[textCount];
stream.Read(textBuffer, 0, textCount);
DB?.CreateRevision(recordIndex, Encoding.UTF8.GetString(textBuffer), false);
Concurrent(() => DeferUpdateRecentNotes());
break;
}
DB?.CreateRevision(recordIndex, string.Empty, false);
Concurrent(() => DeferUpdateRecentNotes());
break;
}
}
public async void Send(MessageType type, byte[] data)
{
if (!DBClient.Connected)
return;
byte[] id = [(byte)type];
byte[] streamData = [.. id, .. data];
try
{
await DBClient.GetStream().WriteAsync(streamData);
}
catch
{
Disconnect();
}
}
public void UpdateIndicator() => Indicator?.Dispatcher.Invoke(() =>
{
Indicator.Fill = Connecting ? Brushes.Yellow : (DBClient?.Connected is true ? Brushes.Green : Brushes.Orange);
Indicator.Height = 12;
Indicator.Margin = new(2, 4, 3, 4);
Indicator.Stroke = Common.Settings.MenuForeground;
Indicator.Width = 12;
Indicator.InvalidateVisual();
DB?.GetHeader();
UpdateContextMenu();
});
}
}