从接口和消息开始。
声明允许对等点交换消息的会话接口。将消息声明为具有简单类型的 C++ 结构,如整数、双精度、std::string 和 std::vector。例如:
// these are your protocol messages
struct HelloRequest {
uint32_t seq_no;
// more stuff
};
struct HelloResponse {
uint32_t seq_no;
// more stuff
};
// Session callback for received messages
struct SessionReceiver {
virtual void connected(Session*) = 0;
virtual void receive(Session* from, HelloRequest msg) = 0;
virtual void receive(Session* from, HelloResponse msg) = 0;
virtual void disconnected(Session*) = 0;
};
// Session interface to send messages
struct Session {
virtual void send(HelloRequest msg) = 0;
virtual void send(HelloResponse msg) = 0;
};
// this connects asynchronously and then calls SessionReceiver::connected() with a newly established session
struct SessionInitiator {
virtual void connect(SessionReceiver* cb, std::string peer) = 0;
};
// this accepts connections asynchronously and then calls SessionReceiver::connected() with a newly accepted session
struct SessionAcceptor {
virtual void listen(SessionReceiver* cb, std::string port) = 0;
};
然后通过编码使用这些接口的业务逻辑来测试您的接口。一旦您确信接口允许您实现所需的逻辑,就可以使用您喜欢的事件驱动框架(如 libevent 或 Boost.Asio)实现接口和消息序列化。
编辑:
请注意,接口允许您进行模拟或测试实现。此外,序列化发生在接口后面的事实意味着,对于进程内对等点,您不必序列化和反序列化消息,您可以按原样传递它们。