-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathMessageClient.cpp
48 lines (39 loc) · 1.18 KB
/
MessageClient.cpp
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
#include "MessageClient.hpp"
#include "PipeStream/MemoryStream.hpp"
MessageClient::MessageClient(PipeStream& _pipe)
: pipe(_pipe)
{
}
//---------------------------------------------------------------------------
std::unique_ptr<IMessage> MessageClient::Receive()
{
MemoryStream ms;
std::vector<uint8_t> buffer(256);
do
{
const auto length = pipe.Read(buffer.data(), 0, static_cast<int>(buffer.size()));
ms.Write(buffer.data(), 0, length);
} while (!pipe.IsMessageComplete());
ms.SetPosition(0);
BinaryReader br(ms);
const auto type = static_cast<MessageType>(br.ReadInt32());
const 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) const
{
MemoryStream ms;
BinaryWriter bw(ms);
bw.Write(static_cast<int>(message.GetMessageType()));
message.WriteTo(bw);
auto data = ms.ToArray();
pipe.Write(data.data(), 0, static_cast<int>(data.size()));
}
//---------------------------------------------------------------------------