Facebook
From Unique Pheasant, 3 Years ago, written in C.
Embed
Download Paste or View Raw
Hits: 79
  1. /*
  2.  Źródło: https://www.geeksforgeeks.org/tcp-server-client-implementation-in-c/
  3.  $ gcc klient_0.c -o klient_0
  4.  
  5. */
  6.  
  7. #include <netdb.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <sys/socket.h>
  12.  
  13. #include <unistd.h>
  14. #include <netinet/in.h>
  15. #include <arpa/inet.h>
  16.  
  17. #define MAX 80
  18. #define PORT 8081
  19. #define SA struct sockaddr
  20. void func(int sockfd)
  21. {
  22.         char buff[MAX];
  23.         int n;
  24.         for (;;) {
  25.                 bzero(buff, sizeof(buff));
  26.                 printf("Enter the string : ");
  27.                 n = 0;
  28.                 while ((buff[n++] = getchar()) != '\n')
  29.                         ;
  30.                 write(sockfd, buff, sizeof(buff));
  31.                 bzero(buff, sizeof(buff));
  32.                 read(sockfd, buff, sizeof(buff));
  33.                 printf("From Server : %s", buff);
  34.                 if ((strncmp(buff, "EXIT", 4)) == 0) {
  35.                         printf("Client Exit...\n");
  36.                         break;
  37.                 }
  38.         }
  39. }
  40.  
  41. int main()
  42. {
  43.         int sockfd, connfd;
  44.         struct sockaddr_in servaddr, cli;
  45.  
  46.         // socket create and varification
  47.         sockfd = socket(AF_INET, SOCK_STREAM, 0);
  48.         if (sockfd == -1) {
  49.                 printf("socket creation failed...\n");
  50.                 exit(0);
  51.         }
  52.         else
  53.                 printf("Socket successfully created..\n");
  54.         bzero(&servaddr, sizeof(servaddr));
  55.  
  56.         // assign IP, PORT
  57.         servaddr.sin_family = AF_INET;
  58.         servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  59.         servaddr.sin_port = htons(PORT);
  60.  
  61.         // connect the client socket to server socket
  62.         if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
  63.                 printf("connection with the server failed...\n");
  64.                 exit(0);
  65.         }
  66.         else
  67.                 printf("connected to the server..\n");
  68.  
  69.         // function for chat
  70.         func(sockfd);
  71.  
  72.         // close the socket
  73.         close(sockfd);
  74. }