protocol.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // MessagePack for C++ example
  2. //
  3. // Copyright (C) 2008-2015 FURUHASHI Sadayuki and KONDO Takatoshi
  4. //
  5. // Distributed under the Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //
  9. #include <msgpack.hpp>
  10. #include <string>
  11. #include <iostream>
  12. #include <sstream>
  13. // This example uses obsolete APIs
  14. // See protocol_new.cpp
  15. namespace myprotocol {
  16. using namespace msgpack::type;
  17. using msgpack::define;
  18. struct Get : define< tuple<uint32_t, std::string> > {
  19. Get() { }
  20. Get(uint32_t f, const std::string& k) :
  21. define_type(msgpack_type(f, k)) { }
  22. uint32_t& flags() { return msgpack::type::get<0>(*this); }
  23. std::string& key() { return msgpack::type::get<1>(*this); }
  24. };
  25. struct Put : define< tuple<uint32_t, std::string, raw_ref> > {
  26. Put() { }
  27. Put(uint32_t f, const std::string& k, const char* valref, uint32_t vallen) :
  28. define_type(msgpack_type( f, k, raw_ref(valref,vallen) )) { }
  29. uint32_t& flags() { return msgpack::type::get<0>(*this); }
  30. std::string& key() { return msgpack::type::get<1>(*this); }
  31. raw_ref& value() { return msgpack::type::get<2>(*this); }
  32. };
  33. struct MultiGet : define< std::vector<Get> > {
  34. };
  35. }
  36. int main(void)
  37. {
  38. // send Get request
  39. std::stringstream stream;
  40. {
  41. myprotocol::Get req;
  42. req.flags() = 0;
  43. req.key() = "key0";
  44. msgpack::pack(stream, req);
  45. }
  46. stream.seekg(0);
  47. // receive Get request
  48. {
  49. std::string buffer(stream.str());
  50. msgpack::object_handle oh =
  51. msgpack::unpack(buffer.data(), buffer.size());
  52. msgpack::object o = oh.get();
  53. myprotocol::Get req;
  54. o.convert(req);
  55. std::cout << "received: " << o << std::endl;
  56. }
  57. stream.str("");
  58. // send MultiGet request
  59. {
  60. myprotocol::MultiGet req;
  61. req.push_back( myprotocol::Get(1, "key1") );
  62. req.push_back( myprotocol::Get(2, "key2") );
  63. req.push_back( myprotocol::Get(3, "key3") );
  64. msgpack::pack(stream, req);
  65. }
  66. stream.seekg(0);
  67. // receive MultiGet request
  68. {
  69. std::string buffer(stream.str());
  70. msgpack::object_handle oh =
  71. msgpack::unpack(buffer.data(), buffer.size());
  72. msgpack::object o = oh.get();
  73. myprotocol::MultiGet req;
  74. o.convert(req);
  75. std::cout << "received: " << o << std::endl;
  76. }
  77. }