-
Notifications
You must be signed in to change notification settings - Fork 0
/
Client.cpp
94 lines (73 loc) · 2.04 KB
/
Client.cpp
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
88
89
90
91
92
93
94
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <strings.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <pthread.h>
using namespace std;
#define MAX_SIZE 2000
#define PORT 4001
int main(int argc, char *argv[]) {
if (argc < 4) {
fprintf(stderr, "use like this : %s priority hostname port\n", argv[0]);
exit(0);
}
struct hostent *server;
int portNo = PORT;
server = gethostbyname(argv[2]);
if (server == NULL) {
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
portNo = atoi(argv[3]);
int priority = atoi(argv[1]);
int sock_desc;
struct sockaddr_in serv_addr;
char sbuff[MAX_SIZE], rbuff[MAX_SIZE];
if ((sock_desc = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("Failed creating socket\n");
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portNo);
if (connect(sock_desc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) <
0) {
printf("Failed to connect to server\n");
return -1;
}
// Send Priority
send(sock_desc, argv[1], strlen(argv[1]), 0);
if (recv(sock_desc, rbuff, MAX_SIZE, 0) == 0) {
perror("Server Disconnected");
close(sock_desc);
exit(0);
} else
cout << "server: " << rbuff << endl;
bzero(rbuff, MAX_SIZE);
if (recv(sock_desc, rbuff, MAX_SIZE, MSG_DONTWAIT) != 0) {
cout << "You: ";
while (fgets(sbuff, MAX_SIZE, stdin) != NULL) {
send(sock_desc, sbuff, strlen(sbuff), 0);
if (recv(sock_desc, rbuff, MAX_SIZE, 0) == 0) {
perror("Server Disconnected");
close(sock_desc);
exit(0);
} else
cout << "server: " << rbuff << endl;
bzero(rbuff, MAX_SIZE); // clean buffer
cout << "You: ";
}
close(sock_desc);
return 0;
}
}