source: network-game/common/MessageProcessor.cpp@ 3de664d

Last change on this file since 3de664d was 198cf2d, checked in by dportnoy <dmp1488@…>, 11 years ago

MessageProcessor handles receiving multiple ACKs for the same message

  • Property mode set to 100644
File size: 1.9 KB
Line 
1#include "MessageProcessor.h"
2
3#include <iostream>
4
5#include "Common.h"
6
7MessageProcessor::MessageProcessor() {
8 lastUsedId = 0;
9}
10
11MessageProcessor::~MessageProcessor() {
12}
13
14int 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
26int 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
50void 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
58void 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}
Note: See TracBrowser for help on using the repository browser.