-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverUDP.cpp
97 lines (73 loc) · 2.13 KB
/
serverUDP.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
#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;
vector<sockaddr_in> clientsocket;
vector<socklen_t> len_socket;
vector<int> serversocket;
int main(int argc, char *argv[]){
if(argc < 2){
cout<< "Missing port number "<<argc<<endl;
exit(0);
}
char msg[1500];
for(int i=1; i<argc; i++){
int port = atoi(argv[i]);
//create sockaddr_in structure
sockaddr_in serverSocket;
serverSocket.sin_family = AF_INET;
serverSocket.sin_port = htons(port);
serverSocket.sin_addr.s_addr = htonl(INADDR_ANY);
//initalize socket
int serverSocketID = socket(AF_INET, SOCK_DGRAM, 0);
if(serverSocketID < 0){
cout<<"error initalizing socket\n";
exit(0);
}
serversocket.push_back(serverSocketID);
//bind the socket to server
int bindport = bind(serverSocketID, (struct sockaddr*)&serverSocket, sizeof(serverSocket));
if(bindport < 0){
cout<<"error binding\n";
exit(0);
}
sockaddr_in clientSocket;
socklen_t len = sizeof(clientSocket);
clientsocket.push_back(clientSocket);
len_socket.push_back(len);
}
cout<<"waiting for message from client...\n";
while(1){
for(int i=0; i<serversocket.size(); i++){
recvfrom(serversocket[i], (char*)&msg, sizeof(msg), 0, (struct sockaddr*)&clientsocket[i], &len_socket[i]);
if(!strcmp(msg, "exit")){
cout<<"Session terminated...\n";
break;
}
cout<<"client "<<i<<": ";
cout<<msg<<endl;
}
string data;
cout<<"Server : ";
getline(cin, data);
strcpy(msg, data.c_str());
if(data == "exit"){
cout<<"Session terminated...\n";
break;
}
for(int i=0; i<serversocket.size(); i++){
sendto(serversocket[i], (char*)&msg, sizeof(msg), 0, (sockaddr*)&clientsocket[i], len_socket[i]);
}
}
//close the socket
for(int i=0; i<serversocket.size(); i++){
close(serversocket[i]);
}
return 0;
}