1 | #include "MessageProcessor.h"
|
---|
2 |
|
---|
3 | #include <iostream>
|
---|
4 |
|
---|
5 | #include "Common.h"
|
---|
6 |
|
---|
7 | MessageProcessor::MessageProcessor() {
|
---|
8 | lastUsedId = 0;
|
---|
9 | }
|
---|
10 |
|
---|
11 | MessageProcessor::~MessageProcessor() {
|
---|
12 | }
|
---|
13 |
|
---|
14 | int MessageProcessor::sendMessage(NETWORK_MSG *msg, int sock, struct sockaddr_in *dest) {
|
---|
15 | msg->id = ++lastUsedId;
|
---|
16 | MessageContainer message(*msg, *dest);
|
---|
17 | sentMessages[msg->id] = message;
|
---|
18 |
|
---|
19 | int ret = sendto(sock, (char*)msg, sizeof(NETWORK_MSG), 0, (struct sockaddr *)dest, sizeof(struct sockaddr_in));
|
---|
20 |
|
---|
21 | cout << "Send a message of type " << msg->type << endl;
|
---|
22 |
|
---|
23 | return ret;
|
---|
24 | }
|
---|
25 |
|
---|
26 | int MessageProcessor::receiveMessage(NETWORK_MSG *msg, int sock, struct sockaddr_in *source) {
|
---|
27 | socklen_t socklen = sizeof(struct sockaddr_in);
|
---|
28 |
|
---|
29 | // assume we don't care about the value of socklen
|
---|
30 | int ret = recvfrom(sock, (char*)msg, sizeof(NETWORK_MSG), 0, (struct sockaddr *)source, &socklen);
|
---|
31 |
|
---|
32 | // add id to the NETWORK_MSG struct
|
---|
33 | if (msg->type == MSG_TYPE_ACK) {
|
---|
34 | if (!sentMessages[msg->id].isAcked) {
|
---|
35 | sentMessages[msg->id].isAcked = true;
|
---|
36 | sentMessages[msg->id].timeAcked = getCurrentMillis();
|
---|
37 | }
|
---|
38 |
|
---|
39 | return -1; // don't do any further processing
|
---|
40 | }else {
|
---|
41 | NETWORK_MSG ack;
|
---|
42 | ack.id = msg->id;
|
---|
43 |
|
---|
44 | sendto(sock, (char*)&ack, sizeof(NETWORK_MSG), 0, (struct sockaddr *)source, sizeof(struct sockaddr_in));
|
---|
45 | }
|
---|
46 |
|
---|
47 | return ret;
|
---|
48 | }
|
---|
49 |
|
---|
50 | void MessageProcessor::resendUnackedMessages(int sock) {
|
---|
51 | map<int, MessageContainer>::iterator it;
|
---|
52 |
|
---|
53 | for(it = sentMessages.begin(); it != sentMessages.end(); it++) {
|
---|
54 | sendto(sock, (char*)&it->second.msg, sizeof(NETWORK_MSG), 0, (struct sockaddr *)&it->second.clientAddr, sizeof(struct sockaddr_in));
|
---|
55 | }
|
---|
56 | }
|
---|
57 |
|
---|
58 | void MessageProcessor::cleanAckedMessages() {
|
---|
59 | map<int, MessageContainer>::iterator it;
|
---|
60 |
|
---|
61 | for(it = sentMessages.begin(); it != sentMessages.end(); it++) {
|
---|
62 | if (it->second.isAcked && (getCurrentMillis() - it->second.timeAcked) > 1000)
|
---|
63 | sentMessages.erase(it);
|
---|
64 | }
|
---|
65 | }
|
---|