-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatServer.cpp
68 lines (61 loc) · 1.78 KB
/
chatServer.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
// Server side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <iostream>
#include <thread>
using namespace std;
#define PORT 8080
#define MAXLINE 1024
// Driver code
int main() {
int sockfd,groupMembers=0;
char buffer[MAXLINE];
char *hello ;
struct sockaddr_in servaddr, cliaddr;
struct sockaddr_in allClients[100];
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
// Filling server information
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Bind the socket with the server address
if ( bind(sockfd, (const struct sockaddr *)&servaddr,
sizeof(servaddr)) < 0 )
{
perror("bind failed");
exit(EXIT_FAILURE);
}
int n;
socklen_t len= sizeof(cliaddr);
while(1){
n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, (struct sockaddr*) &cliaddr, &len);
if(buffer[n-1]=='@'){
allClients[groupMembers++]=cliaddr;
n--;
}
buffer[n] = '\0';
if(buffer[n-1]=='&'){
sendto(sockfd, "@", 1, MSG_CONFIRM, (const struct sockaddr *) &cliaddr, len);
buffer[n-1]='\0';
strcat(buffer,"has left!");
}
printf("%s\n", buffer);
for(int i=0;i<groupMembers;i++)
if(allClients[i].sin_addr.s_addr!=cliaddr.sin_addr.s_addr || allClients[i].sin_port!=cliaddr.sin_port){
sendto(sockfd, (const char *)buffer, strlen(buffer), MSG_CONFIRM, (const struct sockaddr *) &allClients[i], len);
}
}
return 0;
}