source: network-game/common/MessageProcessor.cpp@ 5755e68

Last change on this file since 5755e68 was 5755e68, checked in by dportnoy <dmp1488@…>, 11 years ago

MessageProcessor bug fix

  • Property mode set to 100644
File size: 2.4 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 cout << "Sending message" << endl;
20 cout << "id: " << msg->id << endl;
21 cout << "type: " << msg->type << endl;
22 cout << "buffer: " << msg->buffer << endl;
23
24 int ret = sendto(sock, (char*)msg, sizeof(NETWORK_MSG), 0, (struct sockaddr *)dest, sizeof(struct sockaddr_in));
25
26 cout << "Send a message of type " << msg->type << endl;
27
28 return ret;
29}
30
31int MessageProcessor::receiveMessage(NETWORK_MSG *msg, int sock, struct sockaddr_in *source) {
32 socklen_t socklen = sizeof(struct sockaddr_in);
33
34 // assume we don't care about the value of socklen
35 int ret = recvfrom(sock, (char*)msg, sizeof(NETWORK_MSG), 0, (struct sockaddr *)source, &socklen);
36
37 // add id to the NETWORK_MSG struct
38 if (msg->type == MSG_TYPE_ACK) {
39 if (!sentMessages[msg->id].isAcked) {
40 cout << "Received new ack" << endl;
41 sentMessages[msg->id].isAcked = true;
42 sentMessages[msg->id].timeAcked = getCurrentMillis();
43 }else
44 cout << "Received old ack" << endl;
45
46 return -1; // don't do any further processing
47 }else {
48 if (ret > -1) {
49 cout << "Received message" << endl;
50 cout << "id: " << msg->id << endl;
51 cout << "type: " << msg->type << endl;
52 cout << "buffer: " << msg->buffer << endl;
53 }
54
55 NETWORK_MSG ack;
56 ack.id = msg->id;
57 ack.type = MSG_TYPE_ACK;
58
59 sendto(sock, (char*)&ack, sizeof(NETWORK_MSG), 0, (struct sockaddr *)source, sizeof(struct sockaddr_in));
60 }
61
62 return ret;
63}
64
65void MessageProcessor::resendUnackedMessages(int sock) {
66 map<int, MessageContainer>::iterator it;
67
68 for(it = sentMessages.begin(); it != sentMessages.end(); it++) {
69 sendto(sock, (char*)&it->second.msg, sizeof(NETWORK_MSG), 0, (struct sockaddr *)&it->second.clientAddr, sizeof(struct sockaddr_in));
70 }
71}
72
73void MessageProcessor::cleanAckedMessages() {
74 map<int, MessageContainer>::iterator it = sentMessages.begin();
75
76 while (it != sentMessages.end()) {
77 if (it->second.isAcked && (getCurrentMillis() - it->second.timeAcked) > 1000)
78 sentMessages.erase(it++);
79 else
80 it++;
81 }
82}
Note: See TracBrowser for help on using the repository browser.