[1a3c42d] | 1 | #include "MessageProcessor.h"
|
---|
| 2 |
|
---|
[5a64bea] | 3 | #include <iostream>
|
---|
| 4 |
|
---|
[198cf2d] | 5 | #include "Common.h"
|
---|
| 6 |
|
---|
[5a64bea] | 7 | MessageProcessor::MessageProcessor() {
|
---|
| 8 | lastUsedId = 0;
|
---|
| 9 | }
|
---|
| 10 |
|
---|
| 11 | MessageProcessor::~MessageProcessor() {
|
---|
| 12 | }
|
---|
| 13 |
|
---|
[1a3c42d] | 14 | int MessageProcessor::sendMessage(NETWORK_MSG *msg, int sock, struct sockaddr_in *dest) {
|
---|
[9b5d30b] | 15 | msg->id = ++lastUsedId;
|
---|
[5a64bea] | 16 | MessageContainer message(*msg, *dest);
|
---|
[9b5d30b] | 17 | sentMessages[msg->id] = message;
|
---|
[5a64bea] | 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;
|
---|
[1a3c42d] | 24 | }
|
---|
| 25 |
|
---|
[5a64bea] | 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) {
|
---|
[198cf2d] | 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
|
---|
[5a64bea] | 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;
|
---|
[1a3c42d] | 48 | }
|
---|
| 49 |
|
---|
[5a64bea] | 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 | }
|
---|
[1a3c42d] | 56 | }
|
---|
| 57 |
|
---|
| 58 | void MessageProcessor::cleanAckedMessages() {
|
---|
[af713bc] | 59 | map<int, MessageContainer>::iterator it = sentMessages.begin();
|
---|
[198cf2d] | 60 |
|
---|
[af713bc] | 61 | while (it != sentMessages.end()) {
|
---|
[198cf2d] | 62 | if (it->second.isAcked && (getCurrentMillis() - it->second.timeAcked) > 1000)
|
---|
[9557f92] | 63 | sentMessages.erase(it++);
|
---|
[af713bc] | 64 | else
|
---|
| 65 | it++;
|
---|
[198cf2d] | 66 | }
|
---|
[1a3c42d] | 67 | }
|
---|