-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cpp
More file actions
executable file
·87 lines (69 loc) · 1.6 KB
/
Server.cpp
File metadata and controls
executable file
·87 lines (69 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "Socket.h"
#include <fstream>
#define FILE "out.txt"
void printFile(string file) {
ifstream in(file.c_str());
string content(
(istreambuf_iterator<char>(in)),
istreambuf_iterator<char>()
);
cout << content << endl;
}
char checkSum(char* message) {
char sum = 0;
for (int i = HEADER; i < BUFFER; i++) {
sum += message[i];
}
if (sum == 0) { // a zero would signify end of array
sum++;
}
return sum;
}
int main() {
Socket sock;
ofstream out(FILE);
char sequence = 'A';
int packet = 0;
for (;;) {
sock.receive(false);
cout << "--------------------" << endl;
cout << "Packet: " << packet << endl;
cout << "Seq: " << sequence << endl;
cout << sock.buf << endl;
if (sock.buf[0] != sequence || sock.buf[1] != (int)checkSum(sock.buf)) { // bad packet
if (sock.buf[0] != sequence) {
cout << "NAK - Sequence Error" << endl;
} else {
cout << "NAK - Checksum Error" << endl;
}
char nak[BUFFER];
nak[0] = sequence; // sequence
nak[1] = checkSum(sock.buf); // received checksum
nak[2] = -1; // NAK signal
sock.respond(nak);
}
else { // good packet
cout << packet << ": ACK" << endl;
packet++;
char ack[BUFFER];
ack[0] = sequence; // sequence
ack[1] = checkSum(sock.buf); // received checksum
ack[2] = 1; // ACK signal
sock.respond(ack);
sequence = sequence == 'A' ? 'B' : 'A';
// Copy content buffer to file
for (int i = HEADER; i < BUFFER; i++) {
if (sock.buf[i] == '#') {
break;
}
out << sock.buf[i];
}
if (sock.buf[4] == '#') {
break;
}
}
}
out.close();
printFile("out.txt");
return 0;
}