From 555f65ad7171511d74513b7055552a941a6fe0f2 Mon Sep 17 00:00:00 2001 From: Jon Bergli Heier Date: Thu, 2 Jun 2011 00:17:38 +0200 Subject: Added a Message class with MessageType MSG_TYPE_MSG to transfer text strings. --- .gitignore | 1 + messages.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ messages.h | 17 ++++++++++++++++- 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 5761abc..499a618 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ *.o +*.swp diff --git a/messages.cpp b/messages.cpp index 7bff612..bf50d8c 100644 --- a/messages.cpp +++ b/messages.cpp @@ -127,3 +127,50 @@ void Chunk::get_coords(int64_t& x, int64_t& y) { is.read((char*)&y, sizeof(y)); got_coords = true; } + +/* Message */ + +Message::Message() { + type = MSG_TYPE_MSG; + + str_len = 0; + got_len = false; +} + +Message::Message(std::string msg) { + type = MSG_TYPE_MSG; + + str_len = msg.size(); + + std::ostream os(&b); + os.write((const char*)&str_len, sizeof(str_len)); + os.write(msg.c_str(), str_len); + + got_len = true; +} + +std::size_t Message::payload_size() { + return (got_len ? str_len : sizeof(uint16_t)); +} + +uint16_t Message::get_len() { + std::istream is(&b); + is.read((char*)&str_len, sizeof(str_len)); + + got_len = true; + + return str_len; +} + +std::string Message::get_str() { + std::string s; + + char *buf = new char[str_len]; + std::istream is(&b); + is.read(buf, str_len); + + s.assign(buf, str_len); + delete[] buf; + + return s; +} diff --git a/messages.h b/messages.h index 021c175..a476621 100644 --- a/messages.h +++ b/messages.h @@ -9,7 +9,8 @@ enum MessageType { MSG_TYPE_NONE = 0, MSG_TYPE_HELLO, MSG_TYPE_POS, - MSG_TYPE_CHUNK + MSG_TYPE_CHUNK, + MSG_TYPE_MSG }; class MessageBase { @@ -60,6 +61,20 @@ class Chunk : public MessageBase { void get_coords(int64_t& x, int64_t& y); }; +class Message : public MessageBase { + protected: + uint16_t str_len; + bool got_len; + + public: + Message(); + Message(std::string msg); + + virtual std::size_t payload_size(); + uint16_t get_len(); + std::string get_str(); +}; + } #endif -- cgit v1.2.3