Advertisement
Guest User

network-chat-Program chat

a guest
Oct 17th, 2019
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.19 KB | None | 0 0
  1. #include <sys/socket.h>
  2. #include <netinet/in.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <pthread.h>
  7. #include <unistd.h>
  8. #include <signal.h>
  9.  
  10. #define DEFAULT_PORT 8081
  11. #define BACKLOG 10
  12. #define ENDLESS 1
  13. #define MAX_MESSAGE_SIZE 255
  14.  
  15. int clients_online;
  16. int socket_;
  17. int port;
  18. struct sockaddr_in address;
  19. int clients[BACKLOG];
  20. void send_message(char *text, int from);
  21.  
  22. void sigint_handler(int sig) {
  23.   signal(sig, SIG_IGN);
  24.   printf("\n-%s \n", "SERVER IS TURNING OFF");
  25.   for (size_t i = 0; i < clients_online; ++i) {
  26.     shutdown(clients[i], SHUT_RDWR);
  27.     close(clients[i]);
  28.   }
  29.   printf("-%s \n", "EXIT");
  30.   exit(0);
  31. }
  32.  
  33. void init_server() {
  34.   socket_ = socket(PF_INET, SOCK_STREAM, IPPROTO_IP);
  35.   address.sin_port = htons(port);
  36.   address.sin_family = AF_INET;
  37.   address.sin_addr.s_addr = htonl(INADDR_ANY);
  38. }
  39.  
  40. void chating(void *args) {
  41.   int *client_number = (int *)args;
  42.   char buf[MAX_MESSAGE_SIZE];
  43.  
  44.   while (strcmp(buf, "quit\n") != 0 && strcmp(buf, "quit\r\n") != 0 &&
  45.     strcmp(buf, "quit") != 0) {
  46.     int eos = (int)recv(*client_number, buf, MAX_MESSAGE_SIZE, 0);
  47.     buf[eos] = '\0';
  48.     if (strlen(buf) != 0) {
  49.       send_message(buf, *client_number);
  50.     }
  51.   }
  52.   shutdown(*client_number, SHUT_RDWR);
  53.   close(*client_number);
  54. }
  55.  
  56. void send_message(char *text, int from) {
  57.   char chat_message[MAX_MESSAGE_SIZE + 12];
  58.   sprintf(chat_message, "%d-> %s", from, text);
  59.   for (int i = 0; i < clients_online; ++i) {
  60.     if (clients[i] != from) {
  61.       send(clients[i], chat_message, strlen(chat_message) + 1, 0);
  62.       printf("%s \n", chat_message);
  63.     }
  64.   }
  65. }
  66.  
  67. int main(int argc, char *argv[]) {
  68.   signal(SIGINT, sigint_handler);
  69.  
  70.   if (argc == 2) {
  71.     port = atoi(argv[1]);
  72.   }
  73.   else {
  74.     port = DEFAULT_PORT;
  75.   }
  76.  
  77.   init_server();
  78.  
  79.   if (bind(socket_, &address, sizeof(address)) != 0) {
  80.     perror("BINDING ERROR");
  81.     exit(1);
  82.   }
  83.   listen(socket_, BACKLOG);
  84.  
  85.   pthread_t id[BACKLOG];
  86.   for (clients_online = 0; ENDLESS; ++clients_online) {
  87.     clients[clients_online] = accept(socket_, NULL, NULL);
  88.     pthread_create(&id[clients_online], NULL, &chating, (void *)&clients[clients_online]);
  89.   }
  90.  
  91.   return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement