Advertisement
Combreal

socketServerWIthSelect01.cpp

Nov 3rd, 2019
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.81 KB | None | 0 0
  1. //Example code: A simple server side code, which echos back the received message.
  2. //Handle multiple socket connections with select and fd_set on Linux
  3. #include <stdio.h>
  4. #include <string.h> //strlen
  5. #include <stdlib.h>
  6. #include <errno.h>
  7. #include <iostream>
  8. #include <string>
  9. #include <winsock2.h>
  10. #include <ws2tcpip.h>
  11. #pragma comment(lib, "ws2_32.lib")
  12. #pragma warning( disable : 4996)
  13. using namespace std;
  14.  
  15. #define TRUE 1
  16. #define FALSE 0
  17. #define PORT 5555
  18.  
  19. int main(int argc, char *argv[])
  20. {
  21.     int opt = TRUE;
  22.     int master_socket, addrlen, new_socket, client_socket[30], max_clients = 30, activity, i, valread, sd;
  23.     int max_sd;
  24.     struct sockaddr_in address;
  25.     WSADATA WSAData;
  26.     WSAStartup(MAKEWORD(2, 0), &WSAData);
  27.  
  28.     char buffer[1024]; //data buffer of 1K
  29.  
  30.     //set of socket descriptors
  31.     fd_set readfds;
  32.  
  33.     //a message
  34.     const char *message = "ECHO Daemon v1.0";
  35.  
  36.     //initialise all client_socket[] to 0 so not checked
  37.     for (i = 0; i < max_clients; i++)
  38.     {
  39.         client_socket[i] = 0;
  40.     }
  41.  
  42.     //create a master socket
  43.     if ((master_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0)
  44.     {
  45.         perror("socket failed");
  46.         exit(EXIT_FAILURE);
  47.     }
  48.     //int Socketerror = WSAGetLastError();
  49.     //cout << Socketerror << endl;
  50.  
  51.    
  52.  
  53.     //set master socket to allow multiple connections ,
  54.     //this is just a good habit, it will work without this
  55.     if (setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0)
  56.     {
  57.         perror("setsockopt");
  58.         exit(EXIT_FAILURE);
  59.     }
  60.  
  61.     //type of socket created
  62.     address.sin_family = AF_INET;
  63.     address.sin_addr.s_addr = INADDR_ANY;
  64.     address.sin_port = htons(PORT);
  65.  
  66.     //bind the socket to localhost port 5555
  67.     if (bind(master_socket, (struct sockaddr *)&address, sizeof(address)) < 0)
  68.     {
  69.         perror("bind failed");
  70.         exit(EXIT_FAILURE);
  71.     }
  72.     printf("Listener on port %d \n", PORT);
  73.  
  74.     //try to specify maximum of 3 pending connections for the master socket
  75.     if (listen(master_socket, 3) < 0)
  76.     {
  77.         perror("listen");
  78.         exit(EXIT_FAILURE);
  79.     }
  80.  
  81.     //accept the incoming connection
  82.     addrlen = sizeof(address);
  83.     puts("Waiting for connections ...");
  84.  
  85.     while (TRUE)
  86.     {
  87.         //clear the socket set
  88.         FD_ZERO(&readfds);
  89.  
  90.         //add master socket to set
  91.         FD_SET(master_socket, &readfds);
  92.         max_sd = master_socket;
  93.  
  94.         //add child sockets to set
  95.         for (i = 0; i < max_clients; i++)
  96.         {
  97.             //socket descriptor
  98.             sd = client_socket[i];
  99.  
  100.             //if valid socket descriptor then add to read list
  101.             if (sd > 0)
  102.                 FD_SET(sd, &readfds);
  103.  
  104.             //highest file descriptor number, need it for the select function
  105.             if (sd > max_sd)
  106.                 max_sd = sd;
  107.         }
  108.  
  109.         //wait for an activity on one of the sockets , timeout is NULL ,
  110.         //so wait indefinitely
  111.         activity = select(max_sd + 1, &readfds, NULL, NULL, NULL);
  112.  
  113.         if ((activity < 0) && (errno != EINTR))
  114.         {
  115.             printf("select error");
  116.         }
  117.  
  118.         //If something happened on the master socket ,
  119.         //then its an incoming connection
  120.         if (FD_ISSET(master_socket, &readfds))
  121.         {
  122.             if ((new_socket = accept(master_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0)
  123.             {
  124.                 perror("accept");
  125.                 exit(EXIT_FAILURE);
  126.             }
  127.  
  128.             //inform user of socket number - used in send and receive commands
  129.             printf("New connection , socket fd is %d , ip is : %s , port : %d\n" , new_socket , inet_ntoa(address.sin_addr) , ntohs (address.sin_port));
  130.  
  131.             //send new connection greeting message
  132.             if (send(new_socket, message, strlen(message), 0) != strlen(message))
  133.             {
  134.                 perror("send");
  135.             }
  136.  
  137.             puts("Welcome message sent successfully");
  138.  
  139.             //add new socket to array of sockets
  140.             for (i = 0; i < max_clients; i++)
  141.             {
  142.                 //if position is empty
  143.                 if (client_socket[i] == 0)
  144.                 {
  145.                     client_socket[i] = new_socket;
  146.                     printf("Adding to list of sockets as %d\n", i);
  147.  
  148.                     break;
  149.                 }
  150.             }
  151.         }
  152.  
  153.         //else its some IO operation on some other socket
  154.         for (i = 0; i < max_clients; i++)
  155.         {
  156.             sd = client_socket[i];
  157.  
  158.             if (FD_ISSET(sd, &readfds))
  159.             {
  160.                 //Check if it was for closing , and also read the
  161.                 //incoming message
  162.                 if ((valread = recv(sd, buffer, 1024,0)) < 0)//get data here
  163.                 {
  164.                     //Somebody disconnected , get his details and print
  165.                     getpeername(sd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
  166.                     printf("Host disconnected , ip %s , port %d \n", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
  167.  
  168.                     //Close the socket and mark as 0 in list for reuse
  169.                     closesocket(sd);//close
  170.                     client_socket[i] = 0;
  171.                 }
  172.  
  173.                 //Echo back the message that came in
  174.                 else
  175.                 {
  176.                     //set the string terminating NULL byte on the end
  177.                     //of the data read
  178.                     //here we can use the data sent by client
  179.                     buffer[valread] = '\0';  
  180.                     send(sd, buffer, strlen(buffer), 0);
  181.                 }
  182.             }
  183.         }
  184.     }
  185.  
  186.     system("pause");
  187.     //return 0;
  188. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement