Implementing Packet Framing

Surrounding packets with Int32 6655 to identify packet structure
This commit is contained in:
2021-12-16 16:41:29 +10:00
parent a9bc8c4e7d
commit ece0dffd85
3 changed files with 122 additions and 40 deletions

View File

@ -61,7 +61,7 @@ namespace Articulate_Network
if (clients[i] == null)
{
clients[i] = client;
Console.WriteLine($"Client {i+1} connected from {(client.Client.RemoteEndPoint as IPEndPoint).Address}.");
Console.WriteLine($"Client {i + 1} connected from {(client.Client.RemoteEndPoint as IPEndPoint).Address}.");
break;
}
@ -71,7 +71,7 @@ namespace Articulate_Network
}
}
public async Task<bool> ReceiveData(TcpClient client)
/*public async Task<bool> ReceiveData(TcpClient client)
{
await Task.Run(() =>
{
@ -102,13 +102,83 @@ namespace Articulate_Network
}
catch (SocketException e)
{
for (int i = 0; i < clients.Length; i++)
if (clients[i] == client)
}
}
});
return false;
}*/
public async Task<bool> ReceiveData(TcpClient client)
{
await Task.Run(() =>
{
byte[] buffer = new byte[16384];
int offset = 0;
while (client.Connected)
{
try
{
int bytesToRead = client.Client.Receive(buffer, offset, buffer.Length - offset, SocketFlags.None);
if (bytesToRead == 0)
{
Console.WriteLine("No data.");
continue;
}
var ms = new MemoryStream(buffer);
var br = new BinaryReader(ms);
if (offset > 0)
offset = 0;
while (ms.Position < ms.Length)
{
br.ReadInt32();
int length = (int)br.ReadInt64();
if (length < 0)
break;
if (ms.Position + length > ms.Length)
{
clients[i] = null;
Console.WriteLine($"Client {i+1} lost connection.");
ms.Position -= 8;
buffer = new byte[16384];
offset = (int)(ms.Length - ms.Position);
ms.Read(buffer, 0, offset);
break;
}
ms.Position += length;
int end = (int)br.ReadInt64();
ms.Position -= 8;
if (length == end && length < 1)
break;
ms.Position -= length;
var p = Get<PacketManager>().DeserializePacket(ms);
OnDataReceived(new Articulate_Network.Events.DataReceivedEventArgs()
{
Packet = p,
Client = client
});
br.ReadInt64();
}
}
catch (SocketException e)
{
Console.WriteLine("Client disconnected.");
}
}
});
@ -122,7 +192,10 @@ namespace Articulate_Network
{
byte[] buffer = Get<PacketManager>().SerializePacket(packet);
tcpClient.Client.Send(buffer, buffer.Length, SocketFlags.None);
int sentBytes = tcpClient.Client.Send(buffer, buffer.Length, SocketFlags.None);
if (sentBytes == 0)
Console.WriteLine($"Sent: {sentBytes}");
});
return false;