-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMessageHeader.cs
326 lines (292 loc) · 13.5 KB
/
MessageHeader.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;
using ServerTCP.Models;
namespace ServerTCP
{
/// <summary>
/// Для обработки и отправки сообщений на сервер
/// </summary>
public class MessageHeader
{
public const int LengthAndDataType = 6; // 1 байт тип данных, 5 байт размер
public const string EndMessage = "|0|"; // 1 байт тип данных, 5 байт размер
public enum MessageType : byte
{
Session,
Token,
Login,
Sale,
Registration,
Version,
Programs,
ProgramsPath,
Games,
GamesItemUser,
ProgramsItemUser,
GamesPath,
RecoveryAccount,
Log,
File,
Photo,
Data,
Check,
Title,
TitleLoading,
PublicKey,
}
public MessageType Type { get; }
public MessageLanguages.Languages Language { get; }
public object Message { get; }
public string Token { get; }
public MessageHeader(MessageType type, MessageLanguages.Languages lang, string token)
{
Type = type;
Language = lang;
Token = token;
}
public MessageHeader(MessageType type, string token)
{
Type = type;
Token = token;
}
public MessageHeader(object message, MessageType type, MessageLanguages.Languages lang, string token)
{
Message = message;
Type = type;
Language = lang;
Token = token;
}
public MessageHeader(object message, MessageType type, MessageLanguages.Languages lang)
{
Message = message;
Type = type;
Language = lang;
}
public MessageHeader(object message, MessageType type)
{
Message = message;
Type = type;
}
public MessageHeader(MessageType type, MessageLanguages.Languages lang)
{
Type = type;
Language = lang;
}
public MessageHeader(MessageType type)
{
Type = type;
}
/// <summary>
/// Упаковка сообщения от клиента
/// </summary>
/// <param name="loadToken"></param>
/// <returns></returns>
public byte[] MessageToArray(bool loadToken = false)
{
var message = new byte[]{};
var token = new byte[]{};
switch (Type)
{
case MessageType.Login:
case MessageType.Registration:
case MessageType.RecoveryAccount:
message = Encoding.UTF8.GetBytes(Message.ToString());
break;
case MessageType.Sale:
message = Encoding.UTF8.GetBytes(Message.ToString() + EndMessage);
break;
}
if (loadToken)
token = Encoding.UTF8.GetBytes(Token);
var tokenLength = token.Length;
var messageLength = message.Length;
var lengthByte = messageLength + tokenLength + LengthAndDataType;
var result = new byte[lengthByte];
result[0] = (byte)Type;
result[1] = (byte)Language;
result[2] = loadToken ? (byte)1 : (byte)0; // 1 - токен есть | 0 - без токена(размер токена 10 байт)
var bytes = BitConverter.GetBytes(lengthByte).Where(x => x != 0).ToArray();
if (bytes.Length > 3)
throw new ArgumentException(nameof(bytes));
switch (Type)
{
case MessageType.Login:
case MessageType.Registration:
case MessageType.RecoveryAccount:
Array.Copy(bytes, 0, result, 3, bytes.Length);
Array.Copy(message ?? [0], 0, result, LengthAndDataType, messageLength);
break;
case MessageType.Sale:
Array.Copy(bytes, 0, result, 3, bytes.Length);
Array.Copy(message ?? [0], 0, result, LengthAndDataType, messageLength);
Array.Copy(token ?? [0], 0, result, LengthAndDataType + messageLength, tokenLength);
break;
case MessageType.GamesItemUser:
case MessageType.ProgramsItemUser:
Array.Copy(token ?? [0], 0, result, LengthAndDataType + messageLength, tokenLength);
break;
}
return result;
}
/// <summary>
/// Упаковка сообщения от сервера
/// </summary>
/// <param name="loadToken"></param>
/// <returns></returns>
internal byte[] MessageServerToArray(bool loadToken = false)
{
var message = new byte[] { };
var token = new byte[] { };
switch (Type)
{
case MessageType.Token:
case MessageType.Sale:
case MessageType.Login:
case MessageType.Registration:
case MessageType.TitleLoading:
case MessageType.ProgramsPath:
case MessageType.RecoveryAccount:
case MessageType.GamesPath:
case MessageType.PublicKey:
case MessageType.Version:
case MessageType.Check:
message = Encoding.UTF8.GetBytes(Message.ToString());
break;
case MessageType.Programs:
var xmlProg = new XmlSerializer(typeof(ProgramsForXml));
using (var textWriter = new StringWriter())
{
xmlProg.Serialize(textWriter, Message);
message = Encoding.UTF8.GetBytes(textWriter.ToString());
}
break;
case MessageType.Games:
var xmlGame = new XmlSerializer(typeof(GamesForXml));
using (var textWriter = new StringWriter())
{
xmlGame.Serialize(textWriter, Message);
message = Encoding.UTF8.GetBytes(textWriter.ToString());
}
break;
case MessageType.GamesItemUser:
var xmlSaleGame = new XmlSerializer(typeof(SaleGamesForXml));
using (var textWriter = new StringWriter())
{
xmlSaleGame.Serialize(textWriter, Message);
message = Encoding.UTF8.GetBytes(textWriter.ToString());
}
break;
case MessageType.ProgramsItemUser:
var xmlSaleProg = new XmlSerializer(typeof(SaleProgramsForXml));
using (var textWriter = new StringWriter())
{
xmlSaleProg.Serialize(textWriter, Message);
message = Encoding.UTF8.GetBytes(textWriter.ToString());
}
break;
}
if (loadToken)
token = Encoding.UTF8.GetBytes(Token);
var tokenLength = token.Length;
var messageLength = message.Length;
var lengthByte = messageLength + tokenLength + LengthAndDataType;
var result = new byte[lengthByte];
result[0] = (byte)Type;
result[1] = (byte)Language;
result[2] = loadToken ? (byte)1 : (byte)0; // 1 - токен есть | 0 - без токена(размер токена 10 байт)
var bytes = BitConverter.GetBytes(lengthByte).Where(x => x != 0).ToArray();
if (bytes.Length > 3)
throw new ArgumentException(nameof(bytes));
Array.Copy(bytes, 0, result, 3, bytes.Length);
Array.Copy(message ?? [0], 0, result, LengthAndDataType, messageLength);
return result;
}
/// <summary>
/// Распаковка сообщения
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static MessageHeader FromArray(ReadOnlySpan<byte> buffer)
{
switch ((MessageType)buffer[0])
{
case MessageHeader.MessageType.Version:
case MessageHeader.MessageType.Sale:
case MessageHeader.MessageType.PublicKey:
case MessageHeader.MessageType.Login:
case MessageHeader.MessageType.Registration:
case MessageHeader.MessageType.GamesItemUser:
case MessageHeader.MessageType.ProgramsItemUser:
case MessageHeader.MessageType.TitleLoading:
case MessageHeader.MessageType.RecoveryAccount:
case MessageHeader.MessageType.Programs:
case MessageHeader.MessageType.ProgramsPath:
case MessageHeader.MessageType.Games:
case MessageHeader.MessageType.GamesPath:
case MessageHeader.MessageType.Check:
return new MessageHeader(Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType), (MessageType)buffer[0], (MessageLanguages.Languages)buffer[1]);
break;
case MessageHeader.MessageType.Session:
//return new MessageHeader(Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType), (MessageType)buffer[0], BinaryPrimitives.ReadInt32LittleEndian(buffer[1..])); // сохраняем, добавляем данные. Данные передаются в кодированном формате, будем использовать кодировку UTF8, раскодируем байты
return new MessageHeader((MessageType)buffer[0],
(MessageLanguages.Languages)buffer[1],
Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType));
break;
case MessageHeader.MessageType.Token:
return new MessageHeader((MessageType)buffer[0],
Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType));
break;
//case MessageHeader.MessageType.Login:
// var result = buffer[LengthAndDataType..buffer.Length];
// return new MessageHeader(result.ToArray(),
// (MessageType)buffer[0]);
// break;
default:
return null;
break;
}
}
/// <summary>
/// Распаковка сообщения для сервера
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static MessageHeader ServerFromArray(ReadOnlySpan<byte> buffer)
{
switch ((MessageType)buffer[0])
{
case MessageHeader.MessageType.Version:
case MessageHeader.MessageType.PublicKey:
case MessageHeader.MessageType.Login:
case MessageHeader.MessageType.Programs:
case MessageHeader.MessageType.GamesItemUser:
case MessageHeader.MessageType.ProgramsItemUser:
case MessageHeader.MessageType.ProgramsPath:
case MessageHeader.MessageType.RecoveryAccount:
case MessageHeader.MessageType.Games:
case MessageHeader.MessageType.GamesPath:
case MessageHeader.MessageType.Registration:
case MessageHeader.MessageType.TitleLoading:
case MessageHeader.MessageType.Sale:
case MessageHeader.MessageType.Check:
return new MessageHeader(Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType), (MessageType)buffer[0], (MessageLanguages.Languages)buffer[1]);
break;
case MessageHeader.MessageType.Session:
//return new MessageHeader(Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType), (MessageType)buffer[0], BinaryPrimitives.ReadInt32LittleEndian(buffer[1..])); // сохраняем, добавляем данные. Данные передаются в кодированном формате, будем использовать кодировку UTF8, раскодируем байты
return new MessageHeader((MessageType)buffer[0],
(MessageLanguages.Languages)buffer[1],
Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType));
break;
case MessageHeader.MessageType.Token:
return new MessageHeader((MessageType)buffer[0],
Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType));
break;
default:
return null;
break;
}
}
}
}