-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMessageClient.cs
More file actions
73 lines (61 loc) · 1.49 KB
/
MessageClient.cs
File metadata and controls
73 lines (61 loc) · 1.49 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.IO.Pipes;
using System.Text;
namespace MemoryPipePlugin
{
class MessageClient
{
private readonly PipeStream pipe;
public PipeStream Pipe => pipe;
private readonly Dictionary<int, Func<IMessage>> registeredMessages = new Dictionary<int, Func<IMessage>>();
public IDictionary<int, Func<IMessage>> RegisteredMessages => registeredMessages;
public MessageClient(PipeStream pipe)
{
Contract.Requires(pipe != null);
this.pipe = pipe;
}
public IMessage Receive()
{
using (var ms = new MemoryStream())
{
var buffer = new byte[256];
do
{
var length = pipe.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, length);
}
while (!pipe.IsMessageComplete);
ms.Position = 0;
using (var br = new BinaryReader(ms, Encoding.Unicode, true))
{
var type = br.ReadInt32();
Func<IMessage> createFn;
if (registeredMessages.TryGetValue(type, out createFn))
{
var message = createFn();
message.ReadFrom(br);
return message;
}
}
}
return null;
}
public void Send(IMessage message)
{
Contract.Requires(message != null);
using (var ms = new MemoryStream())
{
using (var bw = new BinaryWriter(ms, Encoding.Unicode, true))
{
bw.Write(message.Type);
message.WriteTo(bw);
}
var buffer = ms.ToArray();
pipe.Write(buffer, 0, buffer.Length);
}
}
}
}