Mihailo21

PeteUDPServer

Nov 21st, 2023
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 7.47 KB | None | 0 0
  1. // UDP server that use non-blocking sockets
  2. #define _WINSOCK_DEPRECATED_NO_WARNINGS
  3. #define WIN32_LEAN_AND_MEAN
  4.  
  5. #include <windows.h>
  6. #include <winsock2.h>
  7. #include <ws2tcpip.h>
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include "conio.h"
  11.  
  12. #pragma comment (lib, "Ws2_32.lib")
  13. #pragma comment (lib, "Mswsock.lib")
  14. #pragma comment (lib, "AdvApi32.lib")
  15.  
  16. // Port numbers of server that will be used for communication with clients
  17. #define SERVER_PORT1 15011 
  18. #define SERVER_PORT2 15012
  19.  
  20. // Size of buffer that will be used for sending and receiving messages to clients
  21. #define BUFFER_SIZE 512    
  22.  
  23. int main()
  24. {
  25.     // Server addresses
  26.     sockaddr_in serverAddress1;
  27.     sockaddr_in serverAddress2;
  28.  
  29.     // Buffer we will use to send and receive clients' messages
  30.     char dataBuffer[BUFFER_SIZE];
  31.  
  32.     // WSADATA data structure that is to receive details of the Windows Sockets implementation
  33.     WSADATA wsaData;
  34.  
  35.     // Initialize windows sockets library for this process
  36.     if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
  37.     {
  38.         printf("WSAStartup failed with error: %d\n", WSAGetLastError());
  39.         return 1;
  40.     }
  41.  
  42.     // Initialize serverAddress1 and serverAddress2 structures used by bind function
  43.     memset((char*)&serverAddress1, 0, sizeof(serverAddress1));
  44.     serverAddress1.sin_family = AF_INET;            // set server address protocol family
  45.     serverAddress1.sin_addr.s_addr = INADDR_ANY;    // use all available addresses of server
  46.     serverAddress1.sin_port = htons(SERVER_PORT1);  // 15001 port
  47.  
  48.     memset((char*)&serverAddress2, 0, sizeof(serverAddress2));
  49.     serverAddress2.sin_family = AF_INET;                            // set server address protocol family
  50.     serverAddress2.sin_addr.s_addr = inet_addr("127.0.0.1");        // loop address
  51.     serverAddress2.sin_port = htons(SERVER_PORT2);                  // 15002 port
  52.  
  53.     // Create first socket
  54.     SOCKET serverSocket1 = socket(AF_INET,      // IPv4 address famly
  55.         SOCK_DGRAM,   // datagram socket
  56.         IPPROTO_UDP); // UDP
  57.  
  58.     // Check if socket creation succeeded
  59.     if (serverSocket1 == INVALID_SOCKET)
  60.     {
  61.         printf("Creating socket failed with error: %d\n", WSAGetLastError());
  62.         WSACleanup();
  63.         return 1;
  64.     }
  65.  
  66.     // Create second socket
  67.     SOCKET serverSocket2 = socket(AF_INET,      // IPv4 address famly
  68.         SOCK_DGRAM,   // datagram socket
  69.         IPPROTO_UDP); // UDP
  70.  
  71.     // Check if socket creation succeeded
  72.     if (serverSocket2 == INVALID_SOCKET)
  73.     {
  74.         printf("Creating socket failed with error: %d\n", WSAGetLastError());
  75.         WSACleanup();
  76.         return 1;
  77.     }
  78.  
  79.     // Bind server address structure (type, port number and local address) to first socket
  80.     int iResult = bind(serverSocket1,(SOCKADDR *)&serverAddress1, sizeof(serverAddress1));
  81.  
  82.     // Check if socket is succesfully binded to server address data
  83.     if (iResult == SOCKET_ERROR)
  84.     {
  85.         printf("Socket bind failed with error: %d\n", WSAGetLastError());
  86.         closesocket(serverSocket1);
  87.         WSACleanup();
  88.         return 1;
  89.     }
  90.  
  91.     // Bind server address structure (type, port number and local address) to second socket
  92.     iResult = bind(serverSocket2,(SOCKADDR *)&serverAddress2, sizeof(serverAddress2));
  93.  
  94.     // Check if socket is succesfully binded to server address data
  95.     if (iResult == SOCKET_ERROR)
  96.     {
  97.         printf("Socket bind failed with error: %d\n", WSAGetLastError());
  98.         closesocket(serverSocket2);
  99.         WSACleanup();
  100.         return 1;
  101.     }
  102.  
  103.     // Setting non-blocking mode to both sockets
  104.     unsigned long mode = 1;
  105.     if(ioctlsocket(serverSocket1, FIONBIO, &mode) != 0 || ioctlsocket(serverSocket2, FIONBIO, &mode) != 0)
  106.     {
  107.         printf("ioctlsocket failed with error %d\n", WSAGetLastError());
  108.         closesocket(serverSocket1);
  109.         closesocket(serverSocket2);
  110.         WSACleanup();
  111.         return 1;
  112.     }
  113.  
  114.     printf("Simple UDP server started and waiting client messages.\n");
  115.  
  116.     // Main server loop
  117.     while (true)
  118.     {
  119.         // Declare and initialize client address that will be set from recvfrom
  120.         sockaddr_in clientAddress;
  121.         memset(&clientAddress, 0, sizeof(clientAddress));
  122.  
  123.         // Set whole buffer to zero
  124.         memset(dataBuffer, 0, BUFFER_SIZE);
  125.  
  126.         // Size of client address
  127.         int sockAddrLen = sizeof(clientAddress);
  128.  
  129.         // Declare and initialize set of socket descriptor for buffer reading
  130.         fd_set readfds;
  131.         FD_ZERO(&readfds);
  132.  
  133.         // Add socket to set readfds
  134.         FD_SET(serverSocket1, &readfds);
  135.         FD_SET(serverSocket2, &readfds);
  136.  
  137.         // Declare and initialize set of socket descriptor for exceptions
  138.         fd_set exceptfds;
  139.         FD_ZERO(&exceptfds);
  140.  
  141.         // Add socket to set exceptfds
  142.         FD_SET(serverSocket1, &exceptfds);
  143.         FD_SET(serverSocket2, &exceptfds);
  144.  
  145.         // Wait new messages to arrive in one of the sockets in readfds set and wait for possible exception on sockets in exceptfds set
  146.         int sResult = select(0, &readfds , NULL , &exceptfds , NULL);
  147.  
  148.         // Check whether the error occurred
  149.         if (sResult == SOCKET_ERROR)
  150.         {
  151.             printf("select failed with error: %d\n", WSAGetLastError());
  152.             break;
  153.         }
  154.  
  155.         // If result is positive, that is indicator that packet has arrived to one or more socket or there is exception on some socket
  156.         // Result number corresonds to number of sockets that have an event
  157.         else if (sResult > 0)
  158.         {
  159.             unsigned long portNumber = 0;
  160.  
  161.             // We will check if packet is arrived to one of our sockets (if two or more sockets are used, we have to check each socket)
  162.             if(FD_ISSET(serverSocket1, &readfds))
  163.             {
  164.                 // Receive client message
  165.                 iResult = recvfrom(serverSocket1,           // Socket with port 15001
  166.                     dataBuffer,                 // Buffer that will be used for receiving message
  167.                     BUFFER_SIZE,                    // Maximal size of buffer
  168.                     0,                          // No flags
  169.                     (SOCKADDR *)&clientAddress, // Client information from received message (ip address and port)
  170.                     &sockAddrLen);              // Size of sockadd_in structure
  171.                 portNumber = SERVER_PORT1;
  172.                 if(iResult != SOCKET_ERROR)
  173.                 {
  174.                     // Set end of string
  175.                     dataBuffer[iResult] = '\0';
  176.  
  177.  
  178.                     printf("Server received message on %d port. Client sent: %s.\n", portNumber,dataBuffer);
  179.                 }
  180.                 else
  181.                 {
  182.                     printf("recvfrom failed with error: %d\n", WSAGetLastError());
  183.                     continue;
  184.                 }
  185.             }
  186.             if(FD_ISSET(serverSocket2, &readfds))
  187.             {
  188.                 // Receive client message
  189.                 iResult = recvfrom(serverSocket2,           // Socket with port 15002
  190.                     dataBuffer,                 // Buffer that will be used for receiving message
  191.                     BUFFER_SIZE,                    // Maximal size of buffer
  192.                     0,                          // No flags
  193.                     (SOCKADDR *)&clientAddress, // Client information from received message (ip address and port)
  194.                     &sockAddrLen);              // Size of sockadd_in structure
  195.                 portNumber = SERVER_PORT2;
  196.                 if(iResult != SOCKET_ERROR)
  197.                 {
  198.                     // Set end of string
  199.                     dataBuffer[iResult] = '\0';
  200.  
  201.  
  202.                     printf("Server received message on %d port. Client sent: %s.\n", portNumber,dataBuffer);
  203.                 }
  204.                 else
  205.                 {
  206.                     printf("recvfrom failed with error: %d\n", WSAGetLastError());
  207.                     continue;
  208.                 }
  209.             }
  210.             // We will check if an exception occurred on one of our sockets. Close server application if error occured
  211.             if(FD_ISSET(serverSocket1, &exceptfds))
  212.             {
  213.                 break;
  214.             }
  215.             if(FD_ISSET(serverSocket2, &exceptfds))
  216.             {
  217.                 break;
  218.             }
  219.             // neither of two socket is in these two sets (some error has occurred)
  220.             else
  221.             {
  222.                 continue;
  223.             }
  224.  
  225.             // Check if message is succesfully received
  226.  
  227.         }
  228.     }
  229.  
  230.     // Close server application
  231.     if (SOCKET_ERROR == closesocket(serverSocket1) || SOCKET_ERROR == closesocket(serverSocket2))
  232.     {
  233.         printf("closesocket failed with error: %ld\n", WSAGetLastError());
  234.         WSACleanup();
  235.         return 1;
  236.     }
  237.  
  238.     printf("Server successfully shut down.\n");
  239.  
  240.     // Close Winsock library
  241.     WSACleanup();
  242.     return 0;
  243. }
Add Comment
Please, Sign In to add comment