-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclientSide.cpp
62 lines (51 loc) · 1.65 KB
/
clientSide.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
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#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[]){
if(argc!=3){
cout<<"Missing hostname and port number";
exit(0);
}
char* serverName=argv[1];
int port=atoi(argv[2]);
char message[1500];
struct hostent* host=gethostbyname(serverName);
sockaddr_in clientSocket;
clientSocket.sin_family=AF_INET;//ipv4
clientSocket.sin_port=htons(port);
clientSocket.sin_addr=**(struct in_addr **)host->h_addr_list;
int clientSocketID=socket(AF_INET,SOCK_STREAM,0);
int status=connect(clientSocketID,(struct sockaddr *)&clientSocket,sizeof(clientSocket));
if(status<0){
cout<<"Connecting error"<<endl;
exit(0);
}
cout<<"Connected successfully!"<<endl;
while(true){
string data;
cout<<"Client :";
getline(cin, data);
strcpy(message,data.c_str());
send(clientSocketID,(char *) &message,sizeof(message),0);
if(data=="exit"){
cout<<"Session terminated"<<endl;
break;
}
cout<<"Server: ";
recv(clientSocketID,(char *)&message,sizeof(message),0);
if(!strcmp(message,"exit")){
cout<<"Session terminated"<<endl;
break;
}
cout<<message<<endl;
}
close(clientSocketID);
return 0;
}