// Copyright 2011, Shuo Chen. All rights reserved. // http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: Shuo Chen (chenshuo at chenshuo dot com) #ifndef MUDUO_EXAMPLES_PROTOBUF_CODEC_DISPATCHER_H #define MUDUO_EXAMPLES_PROTOBUF_CODEC_DISPATCHER_H #include "muduo/base/noncopyable.h" #include "muduo/net/Callbacks.h" #include #include #include typedef std::shared_ptr MessagePtr; class Callback : muduo::noncopyable { public: virtual ~Callback() = default; virtual void onMessage(const muduo::net::TcpConnectionPtr&, const MessagePtr& message, muduo::Timestamp) const = 0; }; template class CallbackT : public Callback { static_assert(std::is_base_of::value, "T must be derived from gpb::Message."); public: typedef std::function& message, muduo::Timestamp)> ProtobufMessageTCallback; CallbackT(const ProtobufMessageTCallback& callback) : callback_(callback) { } void onMessage(const muduo::net::TcpConnectionPtr& conn, const MessagePtr& message, muduo::Timestamp receiveTime) const override { std::shared_ptr concrete = muduo::down_pointer_cast(message); assert(concrete != NULL); callback_(conn, concrete, receiveTime); } private: ProtobufMessageTCallback callback_; }; class ProtobufDispatcher { public: typedef std::function ProtobufMessageCallback; explicit ProtobufDispatcher(const ProtobufMessageCallback& defaultCb) : defaultCallback_(defaultCb) { } void onProtobufMessage(const muduo::net::TcpConnectionPtr& conn, const MessagePtr& message, muduo::Timestamp receiveTime) const { CallbackMap::const_iterator it = callbacks_.find(message->GetDescriptor()); if (it != callbacks_.end()) { it->second->onMessage(conn, message, receiveTime); } else { defaultCallback_(conn, message, receiveTime); } } template void registerMessageCallback(const typename CallbackT::ProtobufMessageTCallback& callback) { std::shared_ptr > pd(new CallbackT(callback)); callbacks_[T::descriptor()] = pd; } private: typedef std::map > CallbackMap; CallbackMap callbacks_; ProtobufMessageCallback defaultCallback_; }; #endif // MUDUO_EXAMPLES_PROTOBUF_CODEC_DISPATCHER_H