-
Notifications
You must be signed in to change notification settings - Fork 0
/
Networking.cs
101 lines (91 loc) · 3.26 KB
/
Networking.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
using Newtonsoft.Json;
using Org.BouncyCastle.Crypto;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using VKanave.Networking.NetMessages;
namespace VKanaveServer.Core
{
internal static class Networking
{
internal static void ReceiveData(Connection connection)
{
NetworkStream stream = connection.Stream;
byte[] data = new byte[NetMessage.BUFFER_SIZE];
bool emptyBuffer = true;
while (true)
{
byte[] receivedData = new byte[NetMessage.BUFFER_SIZE];
stream.Read(receivedData, 0, receivedData.Length);
if (IsBufferEmpty(receivedData))
{
data = data.Concat(receivedData).ToArray();
CheckConnection(connection);
break;
}
else
{
connection.EmptyBuffersCount = 0;
if (!emptyBuffer)
{
data = data.Concat(receivedData).ToArray();
}
else
data = receivedData;
emptyBuffer = false;
}
}
if (emptyBuffer)
{
Program.Log(LogType.Networking, $"Empty buffer received. ({connection.Index})");
return;
}
Program.Log(LogType.SrlzLow, string.Join(' ', data));
Program.Log(LogType.Networking, $"data received. {data.Length} bytes ({connection.Index})");
NetMessage msg = NetMessage.Create(data);
msg.Deserialize();
Program.Log(LogType.SrlzHight, $"{msg} deserialized ({connection.Index})");
Program.Log(LogType.NetMessage, $"<= {msg.GetType().Name} ({connection.Index}/{connection.UserIdFriendly})");
PrcMsg(connection, msg);
}
internal static void Send(Connection connection, NetMessage msg)
{
msg.Serialize();
Program.Log(LogType.SrlzHight, $"{msg} serialized ({connection.Index})");
lock (connection.block)
{
connection.Stream.Write(msg.Buffer);
connection.Stream.Flush();
}
Program.Log(LogType.Networking, $"data sent. {msg.Buffer.Length} bytes ({connection.Index})");
Program.Log(LogType.NetMessage, $"=> {msg.GetType().Name} ({connection.Index}/{connection.UserIdFriendly})");
}
internal static void PrcMsg(Connection from, NetMessage msg)
{
if (msg is NMAction)
(msg as NMAction).Action(from);
}
private static bool IsBufferEmpty(byte[] buffer)
{
foreach (byte b in buffer)
{
if (b != 0)
return false;
}
return true;
}
private static void CheckConnection(Connection connection)
{
connection.EmptyBuffersCount++;
if (connection.EmptyBuffersCount > 20)
connection.Disconnect();
}
}
}