-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.cpp
107 lines (95 loc) · 2.37 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
95
96
97
98
99
100
101
102
103
104
105
106
107
#include<arpa/inet.h>
#include<unistd.h>
#include<netdb.h>
#include<sys/time.h>
#include<sys/wait.h>
#include<bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[])
{
char const *serverName;
int port;
//default server name is 'localhost' and default port number is 2000
if(argc == 1)
{
serverName = "localhost";
port = 2000;
}
else if(argc == 2)
{
serverName = argv[1];
port = 2000;
}
else
{
serverName = argv[1];
port = atoi(argv[2]);
}
char message[1500];
//Get host details
struct hostent* host = gethostbyname(serverName);
//Initialize the sockaddr_in struct for the client socket
sockaddr_in clientSocket;
clientSocket.sin_family = AF_INET;
clientSocket.sin_port = htons(port);
clientSocket.sin_addr = ** (struct in_addr **)host->h_addr_list;
//File descriptor for the client socket
int clientSocketID = socket(AF_INET,SOCK_STREAM,0);
//Connect to the server
//connect(socketID, &serverAddr, addrLen)
int status = connect(clientSocketID,(sockaddr *)&clientSocket,sizeof(clientSocket));
if (status<0)
{
cout<<"Error Connecting"<<endl;
exit(0);
}
cout<<"Successful connection!\n"<<endl;
int choice;
cout << "Enter:\n1-to start a chat with the server\n2-to ask the server to perform mathematical operations"<<endl;
cin>>choice;
//Clear the buffer before the next step
char buffer[1];
cin.getline(buffer, 1);
//Send the user's choice to the server
send(clientSocketID, &choice, sizeof(int), 0);
string instructions;
switch(choice)
{
case 1: instructions = "Enter 'exit' (without quotes) to end the chat.";
break;
case 2: instructions = "Enter expressions ONLY of the form n1 <space> op <space> n2, or 'exit' (without quotes) to disconnect.";
break;
default: instructions = "";
break;
}
if(choice == 1 || choice == 2)
{
cout<<endl;
cout<<instructions<<endl;
//Send and receive data
while(1)
{
cout<<"Client: ";
cin.getline(message, 1500);
send(clientSocketID, (char *) &message, sizeof(message),0);
if(strcmp(message,"exit") == 0)
{
cout<<"Session terminated"<<endl;
break;
}
recv(clientSocketID, (char *) &message, sizeof(message),0);
if (strcmp(message,"exit") == 0)
{
cout<<"Session terminated"<<endl;
break;
}
cout<<"Server: "<<message<<endl;
}
}
else
{
cout<<"Invalid choice"<<endl;
}
//Close the client socket
close(clientSocketID);
}