Advertisement
Guest User

ServerNeblokirajuciFunkcije

a guest
Oct 23rd, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 6.83 KB | None | 0 0
  1. #include <ws2tcpip.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <WinSock2.h>
  5.  
  6. #define DEFAULT_BUFLEN 1024
  7. #define DEFAULT_PORT "27016"
  8. #define SERVER_SLEEP_TIME 50
  9.  
  10. bool InitializeWindowsSockets();
  11. int RecieveData(SOCKET socket, char *recvbuf, int size);
  12. int RecieveSize(SOCKET socket);
  13. int Send(SOCKET socket, char*recvbuf, int size);
  14. int Select(SOCKET socket, char funkcija);
  15.  
  16. int  main(void)
  17. {
  18.     // Socket used for listening for new clients
  19.     SOCKET listenSocket = INVALID_SOCKET;
  20.     // Socket used for communication with client
  21.     SOCKET acceptedSocket = INVALID_SOCKET;
  22.     // variable used to store function return value
  23.     int iResult;
  24.     // Buffer used for storing incoming data
  25.     char recvbuf[DEFAULT_BUFLEN];
  26.    
  27.     if(InitializeWindowsSockets() == false)
  28.     {
  29.         // we won't log anything since it will be logged
  30.         // by InitializeWindowsSockets() function
  31.         return 1;
  32.     }
  33.    
  34.     // Prepare address information structures
  35.     addrinfo *resultingAddress = NULL;
  36.     addrinfo hints;
  37.  
  38.     memset(&hints, 0, sizeof(hints));
  39.     hints.ai_family = AF_INET;       // IPv4 address
  40.     hints.ai_socktype = SOCK_STREAM; // Provide reliable data streaming
  41.     hints.ai_protocol = IPPROTO_TCP; // Use TCP protocol
  42.     hints.ai_flags = AI_PASSIVE;     //
  43.  
  44.     // Resolve the server address and port
  45.     iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &resultingAddress);
  46.     if ( iResult != 0 )
  47.     {
  48.         printf("getaddrinfo failed with error: %d\n", iResult);
  49.         WSACleanup();
  50.         return 1;
  51.     }
  52.  
  53.     // Create a SOCKET for connecting to server
  54.     listenSocket = socket(AF_INET,      // IPv4 address famly
  55.                           SOCK_STREAM,  // stream socket
  56.                           IPPROTO_TCP); // TCP
  57.  
  58.     if (listenSocket == INVALID_SOCKET)
  59.     {
  60.         printf("socket failed with error: %ld\n", WSAGetLastError());
  61.         freeaddrinfo(resultingAddress);
  62.         WSACleanup();
  63.         return 1;
  64.     }
  65.  
  66.     // Setup the TCP listening socket - bind port number and local address
  67.     // to socket
  68.     iResult = bind( listenSocket, resultingAddress->ai_addr, (int)resultingAddress->ai_addrlen);
  69.     if (iResult == SOCKET_ERROR)
  70.     {
  71.         printf("bind failed with error: %d\n", WSAGetLastError());
  72.         freeaddrinfo(resultingAddress);
  73.         closesocket(listenSocket);
  74.         WSACleanup();
  75.         return 1;
  76.     }
  77.  
  78.     // Set socket to nonblocking mode
  79.     unsigned long int nonBlockingMode = 1;
  80.     iResult = ioctlsocket(listenSocket, FIONBIO, &nonBlockingMode);
  81.  
  82.     if (iResult == SOCKET_ERROR)
  83.     {
  84.         printf("ioctlsocket failed with error: %ld\n", WSAGetLastError());
  85.         return 1;
  86.     }
  87.  
  88.  
  89.     // Since we don't need resultingAddress any more, free it
  90.     freeaddrinfo(resultingAddress);
  91.  
  92.     // Set listenSocket in listening mode
  93.     iResult = listen(listenSocket, SOMAXCONN);
  94.     if (iResult == SOCKET_ERROR)
  95.     {
  96.         printf("listen failed with error: %d\n", WSAGetLastError());
  97.         closesocket(listenSocket);
  98.         WSACleanup();
  99.         return 1;
  100.     }
  101.  
  102.     printf("Server initialized, waiting for clients.\n");
  103.  
  104.     do
  105.     {
  106.         // Wait for clients and accept client connections.
  107.         // Returning value is acceptedSocket used for further
  108.         // Client<->Server communication. This version of
  109.         // server will handle only one client.
  110.         Select(listenSocket, 'r');
  111.  
  112.         acceptedSocket = accept(listenSocket, NULL, NULL);
  113.  
  114.         if (acceptedSocket == INVALID_SOCKET)
  115.         {
  116.             printf("accept failed with error: %d\n", WSAGetLastError());
  117.             closesocket(listenSocket);
  118.             WSACleanup();
  119.             return 1;
  120.         }
  121.  
  122.         unsigned long int nonBlockingMode = 1;
  123.         iResult = ioctlsocket(acceptedSocket, FIONBIO, &nonBlockingMode);
  124.  
  125.         if (iResult == SOCKET_ERROR)
  126.         {
  127.             printf("ioctlsocket failed with error: %ld\n", WSAGetLastError());
  128.             return 1;
  129.         }
  130.         int size = RecieveSize(acceptedSocket);
  131.         printf("Primljena velicina: %d\n", size);
  132.         iResult = RecieveData(acceptedSocket, recvbuf, size);
  133.  
  134.     } while (1);
  135.  
  136.     // shutdown the connection since we're done
  137.     iResult = shutdown(acceptedSocket, SD_SEND);
  138.     if (iResult == SOCKET_ERROR)
  139.     {
  140.         printf("shutdown failed with error: %d\n", WSAGetLastError());
  141.         closesocket(acceptedSocket);
  142.         WSACleanup();
  143.         return 1;
  144.     }
  145.  
  146.     // cleanup
  147.     closesocket(listenSocket);
  148.     closesocket(acceptedSocket);
  149.     WSACleanup();
  150.  
  151.     return 0;
  152. }
  153.  
  154. bool InitializeWindowsSockets()
  155. {
  156.     WSADATA wsaData;
  157.     // Initialize windows sockets library for this process
  158.     if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
  159.     {
  160.         printf("WSAStartup failed with error: %d\n", WSAGetLastError());
  161.         return false;
  162.     }
  163.     return true;
  164. }
  165.  
  166. int RecieveSize(SOCKET socket) {
  167.     int iResult;
  168.     int pristigliBajtovi = 0;
  169.     int size;
  170.  
  171.     char recvbuf[sizeof(int)];
  172.  
  173.     // clientAddress will be populated from recvfrom
  174.     sockaddr_in clientAddress;
  175.     memset(&clientAddress, 0, sizeof(sockaddr_in));
  176.  
  177.     // set whole buffer to zero
  178.     memset(recvbuf, 0, sizeof(int));
  179.  
  180.     // Izvuci size (prva 4)
  181.     do
  182.     {
  183.         Select(socket, 'r');
  184.         iResult = recv(socket, (recvbuf + pristigliBajtovi), sizeof(int) - pristigliBajtovi, 0);
  185.  
  186.         pristigliBajtovi += iResult;
  187.  
  188.     } while (pristigliBajtovi < sizeof(int));
  189.  
  190.     size = *(int*)recvbuf;
  191.     return size;
  192. }
  193.  
  194. int RecieveData(SOCKET socket, char *recvbuf, int size) {
  195.  
  196.     int iResult;
  197.     int pristigliBajtovi = 0;
  198.  
  199.     // clientAddress will be populated from recvfrom
  200.     sockaddr_in clientAddress;
  201.     memset(&clientAddress, 0, sizeof(sockaddr_in));
  202.  
  203.     // set whole buffer to zero
  204.     memset(recvbuf, 0, size);
  205.     do
  206.     {
  207.         Select(socket, 'r');
  208.         iResult = recv(socket, (recvbuf + pristigliBajtovi), size - pristigliBajtovi, 0);
  209.  
  210.         pristigliBajtovi += iResult;
  211.  
  212.     } while (pristigliBajtovi < size);
  213.  
  214.     printf("Primljena poruka: %s\n", recvbuf);
  215.     return iResult;
  216. }
  217.  
  218. int Select(SOCKET socket, char funkcija) {
  219.     int iResult;
  220.     do
  221.     {
  222.         // Initialize select parameters
  223.         FD_SET set;
  224.         timeval timeVal;
  225.  
  226.         FD_ZERO(&set);
  227.         // Add socket we will wait to read from
  228.         FD_SET(socket, &set);
  229.  
  230.         // Set timeouts to zero since we want select to return
  231.         // instantaneously
  232.         timeVal.tv_sec = 0;
  233.         timeVal.tv_usec = 0;
  234.  
  235.         if (funkcija == 'r')
  236.         {
  237.             iResult = select(0 /* ignored */, &set, NULL, NULL, &timeVal);
  238.         }
  239.         else
  240.         {
  241.             iResult = select(0 /* ignored */, NULL, &set, NULL, &timeVal);
  242.         }
  243.  
  244.         // lets check if there was an error during select
  245.         if (iResult == SOCKET_ERROR)
  246.         {
  247.             fprintf(stderr, "select failed with error: %ld\n", WSAGetLastError());
  248.             continue;
  249.         }
  250.  
  251.         // now, lets check if there are any sockets ready
  252.         if (iResult == 0)
  253.         {
  254.             // there are no ready sockets, sleep for a while and check again
  255.             Sleep(SERVER_SLEEP_TIME);
  256.             continue;
  257.         }
  258.     } while (iResult <= 0);
  259.     return 1;
  260. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement