Initial commit
[remote/remote-mci.git] / protocols / Message.cc
blob1ff1f7b9bf3727f6b61512a91fc80f1178495fa3
1 #include "Message.h"
2 #include "macros.h"
3 namespace remote { namespace protocols {
5 Message::Message()
7 data = NULL;
8 datalen = 0;
9 recvLen = 0;
12 Message::~Message()
14 if (data) delete data;
15 datalen = 0;
18 bool Message::nonBlockingRecv(int fd)
20 char* p_datalen = (char*)&datalen;
21 int r;
22 uint32_t targetRecvLen;
24 if ( recvLen < sizeof(datalen))
26 // still at the datalen part
27 r = read(fd,p_datalen+recvLen,sizeof(datalen)-recvLen);
28 if (r<=0)
30 int e = errno;
31 log("Recv error %i\n",e);
32 __THROW__("Unable to read message length!");
34 recvLen += r;
36 if ( recvLen < sizeof(datalen) )
38 return false;
40 if ( recvLen == sizeof(datalen) )
42 datalen = ntohl(datalen);
43 if (datalen > 512000) __THROW__("Data too long!");
44 if (data) delete data;
45 data = new uint8_t[datalen];
47 targetRecvLen = datalen + sizeof(datalen);
48 if ( recvLen >= sizeof(datalen) && recvLen < targetRecvLen )
50 r = read(fd,data+recvLen-sizeof(datalen),targetRecvLen-recvLen);
51 if (r<=0)
53 int e = errno;
54 log("Recv error %i\n",e);
55 __THROW__ ("Unable to read message data!");
57 recvLen += r;
58 // printf("Read %u of %u bytes.\n",recvLen-sizeof(datalen),datalen);
60 if (recvLen == targetRecvLen)
62 recvLen = 0;
63 return true;
65 return false;
69 /*void Message::recvMsg(int fd,BaseMsg& msg)
71 if (data) delete data;
72 // read length, then data
73 if (!recv(fd,datalen))
74 __THROW__ ("Unable to receive datalen!");
75 // printf("Reading %u bytes of message data\n",datalen);
76 data = new uint8_t[datalen];
77 if (recv(fd, (char*)data, datalen, MSG_WAITALL) <= 0)
78 __THROW__ ("Unable to send data!");
80 uint32_t len = datalen;
81 // let msg read the buffer
82 msg.read(data,len);
83 // msg.print(stdout);
84 // printf("Done reading %u bytes of message data\n\n\n",datalen);
85 }*/
87 void Message::sendMsg(int fd,BaseMsg& msg)
89 uint32_t len;
90 if (data) delete data;
91 // allocate data
92 datalen = msg.getLength();
93 data = new uint8_t[datalen];
94 len = datalen;
95 // printf("Writing %u bytes of message data\n",datalen);
97 uint8_t* d = data;
98 msg.write(d,len);
99 // msg.print(stdout);
102 // write length, then data
103 if (!send(fd,datalen))
104 __THROW__ ("Unable to send datalen!");
105 if (::send(fd, (char*)data, datalen, 0) != ((int64_t)datalen))
106 __THROW__ ("Unable to send data!");
107 // printf("Done writing %u bytes of message data\n\n\n",datalen);
110 uint32_t Message::getLength()
112 return datalen;
115 uint8_t* Message::getData()
117 return data;