-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMessageClient.cpp
More file actions
52 lines (43 loc) · 1.26 KB
/
MessageClient.cpp
File metadata and controls
52 lines (43 loc) · 1.26 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
#include "MessageClient.hpp"
MessageClient::MessageClient(PipeStream& _pipe)
: pipe(_pipe)
{
}
//---------------------------------------------------------------------------
void MessageClient::RegisterMessage(int type, const std::function<std::unique_ptr<IMessage>()>& creator)
{
registeredMessages[type] = creator;
}
//---------------------------------------------------------------------------
std::unique_ptr<IMessage> MessageClient::Receive()
{
MemoryStream ms;
std::vector<uint8_t> buffer(256);
do
{
auto length = pipe.Read(buffer.data(), 0, (int)buffer.size());
ms.Write(buffer.data(), 0, length);
} while (!pipe.IsMessageComplete());
ms.SetPosition(0);
BinaryReader br(ms);
auto type = br.ReadInt32();
auto it = registeredMessages.find(type);
if (it != std::end(registeredMessages))
{
auto message = it->second();
message->ReadFrom(br);
return message;
}
return nullptr;
}
//---------------------------------------------------------------------------
void MessageClient::Send(const IMessage& message)
{
MemoryStream ms;
BinaryWriter bw(ms);
bw.Write(message.GetType());
message.WriteTo(bw);
auto data = ms.ToArray();
pipe.Write(data.data(), 0, (int)data.size());
}
//---------------------------------------------------------------------------