Advertisement
STANAANDREY

so2 socket client example

Dec 22nd, 2024
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/socket.h>
  5. #include <unistd.h>
  6. #include <netinet/in.h>
  7. #include <sys/socket.h>
  8. #include <netinet/in.h>
  9. #include <arpa/inet.h>
  10. #include <pthread.h>
  11.  
  12. #define BUFF_SIZE (1 << 10)
  13.  
  14. static int sockfd;
  15.  
  16. void *thRoutineRead(void *arg) {
  17.     char buffer[BUFF_SIZE + 1];
  18.     while (fgets(buffer, BUFF_SIZE, stdin))
  19.     {
  20.         write(sockfd, buffer, strlen(buffer));
  21.     }
  22.     close(sockfd); // se inchide socket-ul
  23.     return NULL;
  24. }
  25.  
  26. void *thRoutineDisplay(void *arg) {
  27.     char buffer[BUFF_SIZE + 1];
  28.     int r;
  29.     while ((r = read(sockfd, buffer, BUFF_SIZE)) > 0)
  30.     {
  31.         buffer[r] = 0;
  32.         printf("Received: %s", buffer);
  33.     }
  34.    
  35.     return NULL;
  36. }
  37.  
  38. int main(void) {
  39.  
  40.     struct sockaddr_in server;  // structura sockaddr pentru stocarea adresei si portului destinatie la care se va realiza conexiunea
  41.     if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)  // crearea socket-ului TCP
  42.     {
  43.         perror("socket");
  44.         exit(1);
  45.     }
  46.     memset(&server, 0, sizeof(server)); // initializarea cu 0 a structurii sockaddr
  47.     server.sin_family = AF_INET;        // setarea modului AF_INET obligatoriu pentru aceasta structura
  48.     server.sin_addr.s_addr = inet_addr("127.0.0.1");    // setarea adresei ip la care sa se realizeze conexiunea (in acest caz 127.0.01 - localhost)
  49.     server.sin_port = htons(4556); // setarea portului
  50.     if ((connect(sockfd, (struct sockaddr *)&server, sizeof(server))) < 0) // realizarea conexiunii cu serverul
  51.     {
  52.         perror("connect");
  53.         exit(1);
  54.     }
  55.     printf("Connected\n");
  56.  
  57.  
  58.     pthread_t thRead;
  59.     if (pthread_create(&thRead, NULL, thRoutineRead, NULL) != 0) {
  60.         exit(EXIT_FAILURE);
  61.     }
  62.  
  63.     pthread_t thWrite;
  64.     if (pthread_create(&thWrite, NULL, thRoutineDisplay, NULL) != 0) {
  65.         exit(EXIT_FAILURE);
  66.     }
  67.    
  68.    
  69.     pthread_join(thRead, NULL);
  70.     pthread_join(thWrite, NULL);
  71.  
  72.     return 0;
  73. }
  74.  
  75.  
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement