-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathPipeProtoMessage.cs
80 lines (65 loc) · 2.22 KB
/
PipeProtoMessage.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CefUnityLib
{
public class PipeProtoMessage
{
public byte Opcode;
public byte[] Payload;
public byte[] ToBytes()
{
return PipeProto.BytesToProtoMessage(Payload, Opcode);
}
public void WriteToClientStream(NamedPipeClientStream stream, bool flush)
{
var bytes = ToBytes();
lock (stream)
{
stream.Write(bytes, 0, bytes.Length);
if (flush)
{
stream.Flush();
}
}
}
public static PipeProtoMessage ReadFromStream(Stream stream)
{
int headerLengthExpected = 1 + 1 + 4;
byte[] nextHeader = new byte[headerLengthExpected];
int headerBytesRead = stream.Read(nextHeader, 0, nextHeader.Length);
if (headerBytesRead == headerLengthExpected)
{
byte index = 0;
byte firstByte = nextHeader[index++];
if (firstByte == PipeProto.PACKET_START_MARKER)
{
byte packetOpcode = nextHeader[index++];
UInt32 payloadLength = BitConverter.ToUInt32(new byte[] { nextHeader[index++], nextHeader[index++],
nextHeader[index++], nextHeader[index++] }, 0);
var packetParsed = new PipeProtoMessage
{
Opcode = packetOpcode,
Payload = null
};
if (payloadLength > 0)
{
packetParsed.Payload = new byte[payloadLength];
stream.Read(packetParsed.Payload, 0, (int)payloadLength);
}
return packetParsed;
}
}
if (headerBytesRead == 0)
{
throw new InvalidOperationException("Connection is now closed, cannot read data.");
}
return null;
}
}
}