Advertisement
Mihailo21

TCPServerPostavka1

Nov 20th, 2023
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.94 KB | None | 0 0
  1. #define _WINSOCK_DEPRECATED_NO_WARNINGS
  2.  
  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. #define SERVER_PORT 27016
  17. #define BUFFER_SIZE 256
  18.  
  19. // TCP server that use blocking sockets
  20. int main()
  21. {
  22.     // Socket used for listening for new clients
  23.     SOCKET listenSocket = INVALID_SOCKET;
  24.  
  25.     // Socket used for communication with client
  26.     SOCKET acceptedSocket = INVALID_SOCKET;
  27.  
  28.     // Variable used to store function return value
  29.     int iResult;
  30.  
  31.     // Buffer used for storing incoming data
  32.     char dataBuffer[BUFFER_SIZE];
  33.  
  34.     // WSADATA data structure that is to receive details of the Windows Sockets implementation
  35.     WSADATA wsaData;
  36.  
  37.     // Initialize windows sockets library for this process
  38.     if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
  39.     {
  40.         printf("WSAStartup failed with error: %d\n", WSAGetLastError());
  41.         return 1;
  42.     }
  43.  
  44.  
  45.     // Initialize serverAddress structure used by bind
  46.     sockaddr_in serverAddress;
  47.     memset((char*)&serverAddress, 0, sizeof(serverAddress));
  48.     serverAddress.sin_family = AF_INET;             // IPv4 address family
  49.     serverAddress.sin_addr.s_addr = INADDR_ANY;     // Use all available addresses
  50.     serverAddress.sin_port = htons(SERVER_PORT);    // Use specific port
  51.  
  52.  
  53.     // Create a SOCKET for connecting to server
  54.     listenSocket = socket(AF_INET,      // IPv4 address family
  55.         SOCK_STREAM,  // Stream socket
  56.         IPPROTO_TCP); // TCP protocol
  57.  
  58.     // Check if socket is successfully created
  59.     if (listenSocket == INVALID_SOCKET)
  60.     {
  61.         printf("socket failed with error: %ld\n", WSAGetLastError());
  62.         WSACleanup();
  63.         return 1;
  64.     }
  65.  
  66.     // Setup the TCP listening socket - bind port number and local address to socket
  67.     iResult = bind(listenSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
  68.  
  69.     // Check if socket is successfully binded to address and port from sockaddr_in structure
  70.     if (iResult == SOCKET_ERROR)
  71.     {
  72.         printf("bind failed with error: %d\n", WSAGetLastError());
  73.         closesocket(listenSocket);
  74.         WSACleanup();
  75.         return 1;
  76.     }
  77.  
  78.     // Set listenSocket in listening mode
  79.     iResult = listen(listenSocket, SOMAXCONN);
  80.     if (iResult == SOCKET_ERROR)
  81.     {
  82.         printf("listen failed with error: %d\n", WSAGetLastError());
  83.         closesocket(listenSocket);
  84.         WSACleanup();
  85.         return 1;
  86.     }
  87.  
  88.     printf("Server socket is set to listening mode. Waiting for new connection requests.\n");
  89.  
  90.     do
  91.     {
  92.         // Struct for information about connected client
  93.         sockaddr_in clientAddr;
  94.  
  95.         int clientAddrSize = sizeof(struct sockaddr_in);
  96.  
  97.         // Accept new connections from clients
  98.         acceptedSocket = accept(listenSocket, (struct sockaddr*)&clientAddr, &clientAddrSize);
  99.  
  100.         // Check if accepted socket is valid
  101.         if (acceptedSocket == INVALID_SOCKET)
  102.         {
  103.             printf("accept failed with error: %d\n", WSAGetLastError());
  104.             closesocket(listenSocket);
  105.             WSACleanup();
  106.             return 1;
  107.         }
  108.  
  109.         printf("\nNew client request accepted. Client address: %s : %d\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
  110.  
  111.         do
  112.         {
  113.             // Receive data until the client shuts down the connection
  114.             iResult = recv(acceptedSocket, dataBuffer, BUFFER_SIZE, 0);
  115.  
  116.             if (iResult > 0)    // Check if message is successfully received
  117.             {
  118.                 dataBuffer[iResult] = '\0';
  119.  
  120.                 // Log message text
  121.                 printf("Client sent: %s.\n", dataBuffer);
  122.  
  123.             }
  124.             else if (iResult == 0)  // Check if shutdown command is received
  125.             {
  126.                 // Connection was closed successfully
  127.                 printf("Connection with client closed.\n");
  128.                 closesocket(acceptedSocket);
  129.             }
  130.             else    // There was an error during recv
  131.             {
  132.  
  133.                 printf("recv failed with error: %d\n", WSAGetLastError());
  134.                 closesocket(acceptedSocket);
  135.             }
  136.  
  137.         } while (iResult > 0);
  138.  
  139.         // Here is where server shutdown loguc could be placed
  140.  
  141.     } while (true);
  142.  
  143.     // Shutdown the connection since we're done
  144.     iResult = shutdown(acceptedSocket, SD_BOTH);
  145.  
  146.     // Check if connection is succesfully shut down.
  147.     if (iResult == SOCKET_ERROR)
  148.     {
  149.         printf("shutdown failed with error: %d\n", WSAGetLastError());
  150.         closesocket(acceptedSocket);
  151.         WSACleanup();
  152.         return 1;
  153.     }
  154.  
  155.     //Close listen and accepted sockets
  156.     closesocket(listenSocket);
  157.     closesocket(acceptedSocket);
  158.  
  159.     // Deinitialize WSA library
  160.     WSACleanup();
  161.  
  162.     return 0;
  163. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement