-
Notifications
You must be signed in to change notification settings - Fork 6
/
NetworkStreamExtensions.cs
53 lines (46 loc) · 1.6 KB
/
NetworkStreamExtensions.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
using System;
using System.IO;
using System.Net.Sockets;
using FireLite.Core.Exceptions;
namespace FireLite.Core.Extensions
{
public static class NetworkStreamExtensions
{
public static byte[] ReadNBytes(this NetworkStream networkStream, int n)
{
var buffer = new byte[n];
var bytesRead = 0;
while (bytesRead < n)
{
try
{
var chunk = networkStream.Read(buffer, bytesRead, buffer.Length - bytesRead);
if (chunk == 0)
{
throw new ConnectionException();
}
bytesRead += chunk;
}
catch (IOException)
{
throw new ConnectionException();
}
}
return buffer;
}
public static byte[] ReadPacket(this NetworkStream networkStream)
{
var lengthBuffer = networkStream.ReadNBytes(4);
var packetLength = BitConverter.ToInt32(lengthBuffer, 0);
var buffer = networkStream.ReadNBytes(packetLength);
return buffer;
}
public static void SendPacket(this NetworkStream networkStream, byte[] packetBytes)
{
var lengthBuffer = BitConverter.GetBytes(packetBytes.Length);
networkStream.Write(lengthBuffer, 0, lengthBuffer.Length);
networkStream.Write(packetBytes, 0, packetBytes.Length);
networkStream.Flush();
}
}
}