-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMessageClient.cs
More file actions
84 lines (68 loc) · 1.7 KB
/
MessageClient.cs
File metadata and controls
84 lines (68 loc) · 1.7 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
74
75
76
77
78
79
80
81
82
83
84
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.IO.Pipes;
using System.Text;
namespace MemoryPipePlugin
{
internal class MessageClient : IDisposable
{
private readonly PipeStream pipe;
private readonly Dictionary<MessageType, Func<IMessage>> registeredMessages = new Dictionary<MessageType, Func<IMessage>>();
public IntPtr Id => pipe.SafePipeHandle.DangerousGetHandle();
public MessageClient(PipeStream pipe)
{
Contract.Requires(pipe != null);
this.pipe = pipe;
}
public void Dispose()
{
pipe?.Dispose();
}
public void RegisterMessage<T>() where T : IMessage, new()
{
IMessage MessageCreator() => new T();
registeredMessages.Add(MessageCreator().MessageType, MessageCreator);
}
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 = (MessageType)br.ReadInt32();
if (registeredMessages.TryGetValue(type, out var 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((int)message.MessageType);
message.WriteTo(bw);
}
var buffer = ms.ToArray();
pipe.Write(buffer, 0, buffer.Length);
}
}
}
}