OSDN Git Service

a6b430fd33d3b4802cad07e5cbe8c6045501ebfd
[gikomona/libcore.git] / src / communication.cpp
1 #include <sstream>
2
3 #include <boost/range/algorithm.hpp>
4
5 #include "reference-counter.hpp"
6
7 #include "communication/communication.hpp"
8 #include "communication/message/request.hpp"
9 #include "communication/message/failure.hpp"
10 #include "communication/message/succeed.hpp"
11
12 namespace ipc = boost::interprocess;
13
14 namespace monazilla { namespace GikoMona { namespace core {
15
16 communication::communication(const communicate_id self_id) : self(self_id) {
17     gm_shmem = shared_memory(ipc::open_or_create, shared_memory_name, 1024 * 4);
18
19     my_mailbox = construct_object<mailbox>(create_mailbox_name(self));
20     
21     if(auto obj = find_object<reference_counter>(ref_counter_name)) {
22         auto locker = obj->scoped_lock();
23         ++(*obj);
24     } else {
25         construct_object<reference_counter>(ref_counter_name);
26     }
27 }
28
29 communication::~communication() {
30     disconnect_all();
31     
32     if(auto obj = find_object<reference_counter>(ref_counter_name)) {
33         if(obj->count() == 1) {
34             ipc::shared_memory_object::remove(shared_memory_name);
35         } else {
36             auto locker = obj->scoped_lock();
37             --(*obj);
38         }
39     } else {
40         /* error!!!!! */
41     }
42 }
43
44 bool communication::connect(const communicate_id connect_to) {
45     auto obj = find_object<mailbox>(gm_shmem, create_mailbox_name(connect_to));
46     
47     if(obj) {
48         mailbox_map[connect_to] = *obj;
49         send(connect_to, succeed::find_your_mailbox("").to_string());
50     
51         do {
52             mona_string mail = receive(connect_to);
53         } while(is_same_mail(mail, succeed::allow_you_to_send_mail("")));
54     }
55     
56     return obj;
57 }
58
59 bool communication::disconnect(const communicate_id disconnect_from) {
60     return mailbox_map.erase(disconnect_from);
61 }
62
63 mona_string communication::receive(const communicate_id originator_id) {
64     boost::find_if
65 }
66     
67 bool communication::send_string(const communicate_id to, mona_string&& src) {
68     auto obj = find_object<mailbox>(gm_shmem, create_mailbox_name(to));
69     
70     if(obj) {
71         std::ostringstream str_builder;
72         str_builder << to_string(self) << "-" << src;
73         
74         obj->push_back(str_builder.str());
75     }
76     
77     return obj;
78 }
79
80 std::string communication::create_mailbox_name(const communicate_id mb_user_id) {
81     std::ostringstream str_builder;
82     str_builder << "mailbox:" << to_string(mb_user_id);
83     
84     return str_builder.str();
85 }
86
87 } } }