#include <iostream>
#include <string>
#include "Winsock2.h"
#include <WS2tcpip.h>
#include <chrono>
#pragma comment(lib, "WS2_32.lib")

using namespace std;
using namespace std::chrono;

string GetErrorMsgText(int code) {
    string msgText;
    switch (code) {
    case WSAEINTR:              msgText = "WSAEINTR: Interrupted function call"; break;
    case WSAEACCES:             msgText = "WSAEACCES: Permission denied"; break;
    case WSAEFAULT:             msgText = "WSAEFAULT: Bad address"; break;
    case WSAEINVAL:             msgText = "WSAEINVAL: Invalid argument"; break;
    case WSAEMFILE:             msgText = "WSAEMFILE: Too many open files"; break;
    case WSAEWOULDBLOCK:        msgText = "WSAEWOULDBLOCK: Resource temporarily unavailable"; break;
    case WSAEINPROGRESS:        msgText = "WSAEINPROGRESS: Operation now in progress"; break;
    case WSAEALREADY:           msgText = "WSAEALREADY: Operation already in progress"; break;
    case WSAENOTSOCK:           msgText = "WSAENOTSOCK: Socket operation on non-socket"; break;
    case WSAEDESTADDRREQ:       msgText = "WSAEDESTADDRREQ: Destination address required"; break;
    case WSAEMSGSIZE:           msgText = "WSAEMSGSIZE: Message too long"; break;
    case WSAEPROTOTYPE:         msgText = "WSAEPROTOTYPE: Protocol wrong type for socket"; break;
    case WSAENOPROTOOPT:        msgText = "WSAENOPROTOOPT: Bad protocol option"; break;
    case WSAEPROTONOSUPPORT:    msgText = "WSAEPROTONOSUPPORT: Protocol not supported"; break;
    case WSAESOCKTNOSUPPORT:    msgText = "WSAESOCKTNOSUPPORT: Socket type not supported"; break;
    case WSAEOPNOTSUPP:         msgText = "WSAEOPNOTSUPP: Operation not supported"; break;
    case WSAEPFNOSUPPORT:       msgText = "WSAEPFNOSUPPORT: Protocol family not supported"; break;
    case WSAEAFNOSUPPORT:       msgText = "WSAEAFNOSUPPORT: Address family not supported by protocol family"; break;
    case WSAEADDRINUSE:         msgText = "WSAEADDRINUSE: Address already in use"; break;
    case WSAEADDRNOTAVAIL:      msgText = "WSAEADDRNOTAVAIL: Cannot assign requested address"; break;
    case WSAENETDOWN:           msgText = "WSAENETDOWN: Network is down"; break;
    case WSAENETUNREACH:        msgText = "WSAENETUNREACH: Network is unreachable"; break;
    case WSAENETRESET:          msgText = "WSAENETRESET: Network dropped connection on reset"; break;
    case WSAECONNABORTED:       msgText = "WSAECONNABORTED: Software caused connection abort"; break;
    case WSAECONNRESET:         msgText = "WSAECONNRESET: Connection reset by peer"; break;
    case WSAENOBUFS:            msgText = "WSAENOBUFS: No buffer space available"; break;
    case WSAEISCONN:            msgText = "WSAEISCONN: Socket is already connected"; break;
    case WSAENOTCONN:           msgText = "WSAENOTCONN: Socket is not connected"; break;
    case WSAESHUTDOWN:          msgText = "WSAESHUTDOWN: Cannot send after socket shutdown"; break;
    case WSAETIMEDOUT:          msgText = "WSAETIMEDOUT: Connection timed out"; break;
    case WSAECONNREFUSED:       msgText = "WSAECONNREFUSED: Connection refused"; break;
    case WSAEHOSTDOWN:          msgText = "WSAEHOSTDOWN: Host is down"; break;
    case WSAEHOSTUNREACH:       msgText = "WSAEHOSTUNREACH: No route to host"; break;
    case WSASYSCALLFAILURE:     msgText = "WSASYSCALLFAILURE: System call failure"; break;
    default:                    msgText = "***ERROR***: Unknown error"; break;
    }
    return msgText;
}

string SetErrorMsgText(string msgText, int code) {
    return msgText + " " + GetErrorMsgText(code);
}

int main() {
    WSADATA wsaData;
    SOCKET sS;  // Серверный сокет
    SOCKADDR_IN serv;  // Параметры сервера

    try {
        if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { // библиотека версии 2.2
            throw SetErrorMsgText("Startup error:", WSAGetLastError());
        }
        cout << "Winsock initialized successfully!" << endl;
        
        if ((sS = socket(AF_INET /*ipv4*/, SOCK_STREAM /*stream connection*/, NULL)) == INVALID_SOCKET) { //серверный сокет
            throw SetErrorMsgText("Socket creation error:", WSAGetLastError());
        }
        cout << "Socket created successfully!" << endl;

        serv.sin_family = AF_INET;               // IP-адрасацыя
        serv.sin_port = htons(2000);             // Порт 2000
        serv.sin_addr.s_addr = INADDR_ANY;       // Люббой локальный IP-адрес

        if (bind(sS, (LPSOCKADDR)&serv, sizeof(serv)) == SOCKET_ERROR) { // привязка сокета к порту и ip(любой)
            throw SetErrorMsgText("Bind error:", WSAGetLastError());
        }
        cout << "Socket bound successfully!" << endl;

        if (listen(sS, SOMAXCONN) == SOCKET_ERROR) {
            throw SetErrorMsgText("Listen error:", WSAGetLastError());
        }
        cout << "Socket is listening!" << endl;

        while (true) { 
            SOCKET cS;  // новый сокет для общения с клиентом 
            SOCKADDR_IN clnt;  
            int lclnt = sizeof(clnt);
            memset(&clnt, 0, sizeof(clnt));

            cout << "Waiting for a client to connect..." << endl;
            if ((cS = accept(sS, (sockaddr*)&clnt, &lclnt)) == INVALID_SOCKET) { //ожидание подключения клиента
                throw SetErrorMsgText("Accept error:", WSAGetLastError());
            }
            cout << "Client connected!" << endl;

            wchar_t clientIp[INET_ADDRSTRLEN];
            if (InetNtop(AF_INET, &clnt.sin_addr, clientIp, INET_ADDRSTRLEN) == NULL) { //извлекаются данные клиента
                throw SetErrorMsgText("InetNtop error:", WSAGetLastError());
            }
            cout << "Client IP: " << clientIp << endl;
            cout << "Client Port: " << ntohs(clnt.sin_port) << endl;
            auto start = high_resolution_clock::now();

            char buffer[50];
            while (true) {
                int bytesReceived = recv(cS, buffer, sizeof(buffer), 0);  //получаем сообщение от клиента
                if (bytesReceived == SOCKET_ERROR) {
                    throw SetErrorMsgText("Receive error:", WSAGetLastError());
                }
                if (bytesReceived == 0) {
                    cout << "Client disconnected." << endl;
                    break;
                }
                buffer[bytesReceived] = '\0';
                cout << "Received message from client: " << buffer << endl;
                if (send(cS, buffer, bytesReceived, 0) == SOCKET_ERROR) {// пишем сообщение в буфер
                    throw SetErrorMsgText("Send error:", WSAGetLastError());
                }
            }
            auto stop = high_resolution_clock::now();
            auto duration = duration_cast<seconds>(stop - start);
            cout << "Client session duration: " << duration.count() << " seconds" << endl;

            if (closesocket(cS) == SOCKET_ERROR) {
                throw SetErrorMsgText("Client socket closing error:", WSAGetLastError());
            }
            cout << "Client socket closed successfully!" << endl;
        }

        if (closesocket(sS) == SOCKET_ERROR) {
            throw SetErrorMsgText("Server socket closing error:", WSAGetLastError());
        }
        cout << "Server socket closed successfully!" << endl;

        if (WSACleanup() == SOCKET_ERROR) {
            throw SetErrorMsgText("Cleanup error:", WSAGetLastError());
        }
        cout << "Winsock cleaned up successfully!" << endl;
    }
    catch (const string& errorMsgText) {
        cout << "Exception: " << errorMsgText << endl;
    }

    return 0;
}

Это целый код моего приложения. Я буду отправлять блоки его кода тебе, а ты объяснять каждую строчку максимально подробно