You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.3 KiB
C++

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#pragma once
#include <ipc/IpcChannel.h>
#include <ipc/IpcCodec.h>
#include <rpc/RpcInvoker.h>
#include <string>
#include <iostream>
#include <unistd.h>
// Серверный диспетчер, который получает IpcMessage с канала,
// декодирует его в RPC-вызов, вызывает RpcInvoker и шлёт ответ.
class IpcDispatcher {
public:
IpcDispatcher(IpcChannel& ch, RpcInvoker& invoker)
: channel_(ch)
, invoker_(invoker) {}
// Обработать один запрос. Возвращает false, если получили "пустое"
// сообщение и цикл стоит завершить.
bool handleOnce() {
IpcMessage req = channel_.receive();
if (req.empty()) {
return false;
}
std::string method;
RpcArgs args;
IpcCodec::decodeRequest(req, method, args);
RpcValue result = invoker_.dispatch(method, args);
IpcMessage resp = IpcCodec::encodeResponse(result);
channel_.send(resp);
return true;
}
// Простой цикл обработки до тех пор, пока канал не вернёт пустое сообщение.
void loop() {
while (handleOnce()) {
}
}
private:
IpcChannel& channel_;
RpcInvoker& invoker_;
};