Advertisement
Mihailo21

TCPServerResenje1

Nov 20th, 2023
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 10.95 KB | None | 0 0
  1. #define _WINSOCK_DEPRECATED_NO_WARNINGS
  2. #define WIN32_LEAN_AND_MEAN
  3.  
  4. #include <windows.h>
  5. #include <winsock2.h>
  6. #include <ws2tcpip.h>
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #include "conio.h"
  10.  
  11. #pragma comment (lib, "Ws2_32.lib")
  12. #pragma comment (lib, "Mswsock.lib")
  13. #pragma comment (lib, "AdvApi32.lib")
  14.  
  15. #define SERVER_PORT 27016
  16. #define BUFFER_SIZE 256
  17.  
  18. // TCP server that use blocking sockets
  19. int main()
  20. {
  21.     // Socket used for listening for new clients
  22.     SOCKET listenSocket = INVALID_SOCKET;
  23.  
  24.     // Socket used for communication with clients
  25.     SOCKET acceptedSocket1 = INVALID_SOCKET;
  26.     SOCKET acceptedSocket2 = INVALID_SOCKET;
  27.  
  28.     // Variable used to store function return value
  29.     int iResult;
  30.     bool first, second;
  31.     bool quit1, quit2;
  32.  
  33.     int words1, words2;
  34.     int length1, length2;
  35.  
  36.  
  37.     // Buffer used for storing incoming data
  38.     char dataBuffer1[BUFFER_SIZE];
  39.     char dataBuffer2[BUFFER_SIZE];
  40.  
  41.     // WSADATA data structure that is to receive details of the Windows Sockets implementation
  42.     WSADATA wsaData;
  43.  
  44.     // Initialize windows sockets library for this process
  45.     if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
  46.     {
  47.         printf("WSAStartup failed with error: %d\n", WSAGetLastError());
  48.         return 1;
  49.     }
  50.  
  51.  
  52.     // Initialize serverAddress structure used by bind
  53.     sockaddr_in serverAddress;
  54.     memset((char*)&serverAddress, 0, sizeof(serverAddress));
  55.     serverAddress.sin_family = AF_INET;             // IPv4 address family
  56.     serverAddress.sin_addr.s_addr = INADDR_ANY;     // Use all available addresses
  57.     serverAddress.sin_port = htons(SERVER_PORT);    // Use specific port
  58.  
  59.  
  60.     // Create a SOCKET for connecting to server
  61.     listenSocket = socket(AF_INET,      // IPv4 address family
  62.         SOCK_STREAM,  // Stream socket
  63.         IPPROTO_TCP); // TCP protocol
  64.  
  65. // Check if socket is successfully created
  66.     if (listenSocket == INVALID_SOCKET)
  67.     {
  68.         printf("socket failed with error: %ld\n", WSAGetLastError());
  69.         WSACleanup();
  70.         return 1;
  71.     }
  72.  
  73.     // Setup the TCP listening socket - bind port number and local address to socket
  74.     iResult = bind(listenSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
  75.  
  76.     // Check if socket is successfully binded to address and port from sockaddr_in structure
  77.     if (iResult == SOCKET_ERROR)
  78.     {
  79.         printf("bind failed with error: %d\n", WSAGetLastError());
  80.         closesocket(listenSocket);
  81.         WSACleanup();
  82.         return 1;
  83.     }
  84.  
  85.     // Set listenSocket in listening mode
  86.     iResult = listen(listenSocket, SOMAXCONN);
  87.     if (iResult == SOCKET_ERROR)
  88.     {
  89.         printf("listen failed with error: %d\n", WSAGetLastError());
  90.         closesocket(listenSocket);
  91.         WSACleanup();
  92.         return 1;
  93.     }
  94.  
  95.     printf("Server socket is set to listening mode. Waiting for new connection requests.\n");
  96.  
  97.     do
  98.     {
  99.         // Struct for information about connected client
  100.         sockaddr_in clientAddr;
  101.  
  102.         int clientAddrSize = sizeof(struct sockaddr_in);
  103.  
  104.         // Accept new connections from clients
  105.         acceptedSocket1 = accept(listenSocket, (struct sockaddr*)&clientAddr, &clientAddrSize);
  106.  
  107.         // Check if accepted socket is valid
  108.         if (acceptedSocket1 == INVALID_SOCKET)
  109.         {
  110.             printf("accept failed with error: %d\n", WSAGetLastError());
  111.             closesocket(listenSocket);
  112.             WSACleanup();
  113.             return 1;
  114.         }
  115.  
  116.         printf("\nFirst client request accepted. Client address: %s : %d\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
  117.  
  118.         //accept the second client
  119.         acceptedSocket2 = accept(listenSocket, (struct sockaddr*)&clientAddr, &clientAddrSize);
  120.  
  121.         // Check if accepted socket is valid
  122.         if (acceptedSocket2 == INVALID_SOCKET)
  123.         {
  124.             printf("accept failed with error: %d\n", WSAGetLastError());
  125.             closesocket(listenSocket);
  126.             closesocket(acceptedSocket1);
  127.             WSACleanup();
  128.             return 1;
  129.         }
  130.  
  131.         printf("\nSecond client request accepted. Client address: %s : %d\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
  132.  
  133.         printf("Enter a letter on which play starts: ");
  134.         char slovo;
  135.         scanf_s(" %c", &slovo);
  136.         getchar();
  137.  
  138.         sprintf_s(dataBuffer1, "Pocinje igra na slovo na slovo %c. Posaljite vasu rec!\n", slovo);
  139.         sprintf_s(dataBuffer2, "Pocinje igra na slovo na slovo %c. Posaljite vasu rec!\n", slovo);
  140.  
  141.         words1 = words2 = 0;    //count number of correct words of first and second player
  142.         length1 = length2 = 0;  //total length of correct words of first and second player
  143.         quit1 = quit2 = false;  //indicates if player quits the game
  144.         bool end = false;     // indicator of the game end
  145.  
  146.         do
  147.         {
  148.             // Send message to clients using connected socket
  149.             iResult = send(acceptedSocket1, dataBuffer1, (int)strlen(dataBuffer1), 0);
  150.  
  151.             // Check result of send function
  152.             if (iResult == SOCKET_ERROR)
  153.             {
  154.                 printf("send failed with error: %d\n", WSAGetLastError());
  155.                 shutdown(acceptedSocket1, SD_BOTH);
  156.                 shutdown(acceptedSocket2, SD_BOTH);
  157.                 closesocket(acceptedSocket1);
  158.                 closesocket(acceptedSocket2);
  159.                 break;
  160.             }
  161.  
  162.             iResult = send(acceptedSocket2, dataBuffer2, (int)strlen(dataBuffer2), 0);
  163.  
  164.             // Check result of send function
  165.             if (iResult == SOCKET_ERROR)
  166.             {
  167.                 printf("send failed with error: %d\n", WSAGetLastError());
  168.                 shutdown(acceptedSocket1, SD_BOTH);
  169.                 shutdown(acceptedSocket2, SD_BOTH);
  170.                 closesocket(acceptedSocket1);
  171.                 closesocket(acceptedSocket2);
  172.                 break;
  173.             }
  174.  
  175.             //if the play between two players ends
  176.             if (end)
  177.                 break;
  178.  
  179.  
  180.             // Receive data from first client
  181.             iResult = recv(acceptedSocket1, dataBuffer1, BUFFER_SIZE, 0);
  182.  
  183.             if (iResult > 0)    // Check if message is successfully received
  184.             {
  185.                 dataBuffer1[iResult] = '\0';
  186.  
  187.                 // Log message text
  188.                 printf("Client 1 sent: %s.\n", dataBuffer1);
  189.  
  190.                 if (!strcmp(dataBuffer1, "Kraj"))  //first player is quitting the game
  191.                 {
  192.                     quit1 = true;
  193.                     first = false;
  194.                 }
  195.                 else
  196.                 {
  197.                     //check if player sent word on selected letter.
  198.                     // Change letter in upper-case to include both small and big letters
  199.                     if (toupper(dataBuffer1[0]) == toupper(slovo))
  200.                     {
  201.                         printf("Correct word! \n");
  202.                         first = true;
  203.                         words1++;
  204.                         length1 += strlen(dataBuffer1);
  205.                     }
  206.                     else
  207.                     {
  208.                         printf("Incorrect word! \n");
  209.                         first = false;
  210.                     }
  211.                 }
  212.  
  213.             }
  214.             else if (iResult == 0)  // Check if shutdown command is received
  215.             {
  216.                 // Connection was closed successfully
  217.                 printf("Connection with first client closed.\n");
  218.                 shutdown(acceptedSocket2, SD_BOTH);
  219.                 closesocket(acceptedSocket1);
  220.                 closesocket(acceptedSocket2);
  221.                 break;
  222.             }
  223.             else    // There was an error during recv
  224.             {
  225.  
  226.                 printf("recv failed with error: %d\n", WSAGetLastError());
  227.                 shutdown(acceptedSocket1, SD_BOTH);
  228.                 shutdown(acceptedSocket2, SD_BOTH);
  229.                 closesocket(acceptedSocket1);
  230.                 closesocket(acceptedSocket2);
  231.                 break;
  232.             }
  233.  
  234.  
  235.             // Receive data from second client
  236.             iResult = recv(acceptedSocket2, dataBuffer2, BUFFER_SIZE, 0);
  237.  
  238.             if (iResult > 0)    // Check if message is successfully received
  239.             {
  240.                 dataBuffer2[iResult] = '\0';
  241.  
  242.                 // Log message text
  243.                 printf("Client 2 sent: %s.\n", dataBuffer2);
  244.  
  245.                 if (!strcmp(dataBuffer2, "Kraj"))    //second player is quitting
  246.                 {
  247.                     quit2 = true;
  248.                     second = false;
  249.  
  250.                 }
  251.                 else
  252.                 {
  253.                     //check if player sent word on selected letter
  254.                     // Change letter in upper-case to include both small and big letters
  255.                     if (toupper(dataBuffer2[0]) == toupper(slovo))
  256.                     {
  257.                         printf("Correct word! \n");
  258.                         second = true;
  259.                         words2++;
  260.                         length2 += strlen(dataBuffer2);
  261.                     }
  262.                     else
  263.                     {
  264.                         printf("Incorrect word! \n");
  265.                         second = false;
  266.                     }
  267.                 }
  268.  
  269.             }
  270.             else if (iResult == 0)  // Check if shutdown command is received
  271.             {
  272.                 // Connection was closed successfully
  273.                 printf("Connection with client closed.\n");
  274.                 shutdown(acceptedSocket1, SD_BOTH);
  275.                 closesocket(acceptedSocket1);
  276.                 closesocket(acceptedSocket2);
  277.                 break;
  278.             }
  279.             else    // There was an error during recv
  280.             {
  281.  
  282.                 printf("recv failed with error: %d\n", WSAGetLastError());
  283.                 shutdown(acceptedSocket1, SD_BOTH);
  284.                 shutdown(acceptedSocket2, SD_BOTH);
  285.                 closesocket(acceptedSocket1);
  286.                 closesocket(acceptedSocket2);
  287.                 break;
  288.             }
  289.  
  290.             // the play continues if both clients have good words or both mistake
  291.             if (first == second)
  292.             {
  293.                 strcpy_s(dataBuffer1, "Please send next word on chosen letter.");
  294.                 strcpy_s (dataBuffer2, "Please send next word on chosen letter.");
  295.             }
  296.             //one has mistaken other has right word (he is the winner)
  297.             else
  298.             {
  299.                 //first player wins
  300.                 if (first)
  301.                 {
  302.                     sprintf_s(dataBuffer1, "Prvi igrac je poslao %d ispravnih reci, drugi igrac je poslao %d ispravnih reci. Vi ste POBEDILI!\n", words1, words2);
  303.                     sprintf_s(dataBuffer2, "Prvi igrac je poslao %d ispravnih reci, drugi igrac je poslao %d ispravnih reci. Vi ste IZGUBILI!\n", words1, words2);
  304.                     end = true;
  305.                 }
  306.                 //second player wins
  307.                 if (second)
  308.                 {
  309.                     sprintf_s(dataBuffer1, "Prvi igrac je poslao %d ispravnih reci, drugi igrac je poslao %d ispravnih reci. Vi ste IZGUBILI!\n", words1, words2);
  310.                     sprintf_s(dataBuffer2, "Prvi igrac je poslao %d ispravnih reci, drugi igrac je poslao %d ispravnih reci. Vi ste POBEDILI!\n", words1, words2);
  311.                     end = true;
  312.                 }
  313.  
  314.             }
  315.             // if both players quit at the same time
  316.             if (quit1 && quit2)
  317.             {
  318.                 if (length1 > length2)
  319.                 {
  320.                     sprintf_s(dataBuffer1, "Prvi igrac je poslao %d ispravnih reci, drugi igrac je poslao %d ispravnih reci. Ukupna duzina vasih reci je veca. Vi ste POBEDILI!\n", words1, words2);
  321.                     sprintf_s(dataBuffer2, "Prvi igrac je poslao %d ispravnih reci, drugi igrac je poslao %d ispravnih reci. Ukupna duzina vasih reci je kraca.Vi ste IZGUBILI!\n", words1, words2);
  322.                     end = true;
  323.                 }
  324.                 else
  325.                 {
  326.                     sprintf_s(dataBuffer1, "Prvi igrac je poslao %d ispravnih reci, drugi igrac je poslao %d ispravnih reci.Ukupna duzina vasih reci je kraca. Vi ste IZGUBILI!\n", words1, words2);
  327.                     sprintf_s(dataBuffer2, "Prvi igrac je poslao %d ispravnih reci, drugi igrac je poslao %d ispravnih reci.Ukupna duzina vasih reci je veca. Vi ste POBEDILI!\n", words1, words2);
  328.                     end = true;
  329.                 }
  330.             }
  331.  
  332.  
  333.         } while (true);
  334.  
  335.  
  336.     } while (true);
  337.  
  338.     // Shutdown the connection since we're done
  339.     iResult = shutdown(acceptedSocket1, SD_BOTH);
  340.  
  341.     // Check if connection is succesfully shut down.
  342.     if (iResult == SOCKET_ERROR)
  343.     {
  344.         printf("shutdown failed with error: %d\n", WSAGetLastError());
  345.         closesocket(acceptedSocket1);
  346.         closesocket(acceptedSocket2);
  347.         WSACleanup();
  348.         return 1;
  349.     }
  350.  
  351.     // Shutdown the connection since we're done
  352.     iResult = shutdown(acceptedSocket2, SD_BOTH);
  353.  
  354.     // Check if connection is succesfully shut down.
  355.     if (iResult == SOCKET_ERROR)
  356.     {
  357.         printf("shutdown failed with error: %d\n", WSAGetLastError());
  358.         closesocket(acceptedSocket1);
  359.         closesocket(acceptedSocket2);
  360.         WSACleanup();
  361.         return 1;
  362.     }
  363.     //Close listen and accepted sockets
  364.     closesocket(listenSocket);
  365.     closesocket(acceptedSocket1);
  366.     closesocket(acceptedSocket2);
  367.  
  368.     // Deinitialize WSA library
  369.     WSACleanup();
  370.  
  371.     return 0;
  372. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement