-
Notifications
You must be signed in to change notification settings - Fork 1
/
VoteServerTCP.c
executable file
·67 lines (61 loc) · 2.16 KB
/
VoteServerTCP.c
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
//
// Created by tw on 2018/3/2.
//
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Practical.h"
#include "VoteProtocol.h"
#include "VoteEncoding.h"
#include "Framer.h"
static uint64_t counts[MAX_CANDIDATE + 1];
int main(int argc, char *argv[]) {
if (argc != 2)
DieWithUserMessage("Parametes(s)", "<Server Port/Service>");
int servSock = SetupTCPServerSocket(argv[1]);
for (;;)
{
int clntSock = AcceptTCPConnection(servSock);
//Create an input stream from the socket
FILE *channel = fdopen(clntSock, "r+");
if (channel == NULL)
DieWithSystemMessage("fdopen() failed");
//Receive messages until connection closes;
int mSize;
uint8_t inBuf[MAX_WIRE_SIZE];
VoteInfo v;
while ((mSize = GetNextMsg(channel, inBuf, MAX_WIRE_SIZE)) > 0) {
memset(&v, 0, sizeof(v));
printf("Recevied message (%d bytes)\n", mSize);
if (Decode(inBuf, mSize, &v)) {
if (!v.isResponse) {
v.isResponse = true;
if (v.condidate >= 0 && v.condidate <= MAX_CANDIDATE) {
if (!v.isInquiry)
counts[v.condidate] += 1;
v.count = counts[v.condidate];
}
}
uint8_t outBuf[MAX_WIRE_SIZE];
mSize = Encode(&v, outBuf, MAX_WIRE_SIZE);
if (PutMsg(outBuf, mSize, channel) < 0) {
fputs("Error framing/outputting message\n",stdout);
break;
} else {
printf("Processed %s for candidate %d;current count is %llu.\n", (v.isInquiry ? "inquiry" : "vote"), v.condidate, v.count);
}
fflush(channel);
} else {
fputs("Parse error, closing connection.\n", stderr);
break;
}
}
puts("Client finished");
fclose(channel);
}
}