-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVoteClientTCP.c
More file actions
executable file
·72 lines (62 loc) · 2.01 KB
/
VoteClientTCP.c
File metadata and controls
executable file
·72 lines (62 loc) · 2.01 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
//
// Created by tw on 2018/3/2.
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "Practical.h"
#include "VoteProtocol.h"
#include "Framer.h"
#include "VoteEncoding.h"
int main(int argc, char *argv[]) {
if (argc < 3 || argc > 4)
DieWithUserMessage("Parameter(s)", "<Server> <Port/Services> <candiate>[I]");
char *server = argv[1];
char *service = argv[2];
int candi = atoi(argv[3]);
if (candi < 0 || candi > MAX_CANDIDATE)
DieWithUserMessage("Candidate # not valid", argv[3]);
bool inq = argc > 4 && strcmp(argv[4], "I") == 0;
//Create a connection TCP socket
int sock = SetupTCPClientSocket(server, service);
if (sock < 0)
DieWithUserMessage("SetupTCPClientSocket() falied", "unable to connect");
FILE *str = fdopen(sock, "r+");
if (str == NULL)
DieWithSystemMessage("fdopen() failed");
//Set up info for a request
VoteInfo vi;
memset(&vi, 0, sizeof(vi));
vi.isInquiry = inq;
vi.condidate = candi;
uint8_t outBuf[MAX_WIRE_SIZE];
size_t reqSize = Encode(&vi, outBuf, MAX_WIRE_SIZE);
printf("Sending %d-byte %s for candidate %d..\n", reqSize, (
inq ? "inquiry" : "vote"), candi);
//Frame and send
if (PutMsg(outBuf, reqSize, str) < 0)
DieWithSystemMessage("PutMsg() failed");
//Receive and print response
uint8_t inBuf[MAX_WIRE_SIZE];
size_t resSize = GetNextMsg(str, inBuf, MAX_WIRE_SIZE);
if (Decode(inBuf, resSize, &vi)) {
printf("Received:\n");
if (vi.isResponse)
printf("Response to ");
if (vi.isInquiry)
printf("inquiry");
else
printf("vote ");
printf("for candidate %d\n", vi.condidate);
if (vi.isResponse)
printf(" count = %llu\n", vi.count);
}
fclose(str);
exit(0);
}