@232321fdsa

Ничего не происходит при подключении к серверу winssock2. Что делать?

Запускаю сервер, все нормально и он работает, но при попытке подключения для клиента код клиента доходит до фукнции connect и программа ничего не пишет

вот код сервера
#pragma comment(lib, "ws2_32.lib")
#include "WinSock2.h"
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>

#pragma warning(disable : 4996)

std::vector<SOCKET> clients;  
std::mutex clientsMutex;  

void msgAccept(SOCKET clientSocket) {
    char msg[256];
    while (true) {
        int bytesReceived = recv(clientSocket, msg, sizeof(msg), NULL);
        if (bytesReceived > 0) {
            msg[bytesReceived] = '\0';
            std::cout << "Received: " << msg << std::endl;
            for (SOCKET sock : clients) {
                if (sock != clientSocket) {  
                    send(sock, msg, bytesReceived, NULL);
                }
            }

        }
        else if (bytesReceived == 0) {
            std::cout << "Connection closed." << std::endl;
        }
        else {
            std::cerr << "recv failed with error: " << WSAGetLastError() << std::endl;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }


    closesocket(clientSocket);
    std::lock_guard<std::mutex> lock(clientsMutex);
    clients.erase(std::remove(clients.begin(), clients.end(), clientSocket), clients.end());
}

int main() {
    WSADATA wsaData;
    WORD DLLversion = MAKEWORD(2, 1);

    if (WSAStartup(DLLversion, &wsaData) != 0) {
        std::cerr << "\n\n\t\t\t\tLibrary not installed\n\n";
        return 1;
    }

    SOCKADDR_IN addr;
    int sizeOfAddr = sizeof(addr);

    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(1111);
    addr.sin_family = AF_INET;

    SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, NULL);
    if (bind(listenSocket, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) {
        std::cerr << "Bind failed with error: " << WSAGetLastError() << std::endl;
        return 1;
    }

    if (listen(listenSocket, SOMAXCONN) == SOCKET_ERROR) {
        std::cerr << "Listen failed with error: " << WSAGetLastError() << std::endl;
        return 1;
    }

    std::cout << "\n\n\t\t\t\tServer started\n\n";

    while (true) {
        SOCKET clientSocket = accept(listenSocket, (SOCKADDR*)&addr, &sizeOfAddr);
        std::cout << "yeeeees";
        if (clientSocket == INVALID_SOCKET) {
            std::cerr << "Accept failed with error: " << WSAGetLastError() << std::endl;
            continue;
        }

        std::cout << "Client connected\n";
        {
            std::lock_guard<std::mutex> lock(clientsMutex);
            clients.push_back(clientSocket);
        }

        std::thread clientThread(msgAccept, clientSocket);
        clientThread.detach();
    }
    
    closesocket(listenSocket);
    WSACleanup();

    return 0;
}


и код клиента
#pragma comment(lib, "ws2_32.lib")
#include "WinSock2.h"
#include <iostream>
#include <thread>

#pragma warning(disable : 4996)

SOCKET ConnectionClient;

void msgAccept() {
    char msg[256];
    while (true) {
        int bytesReceived = recv(ConnectionClient, msg, sizeof(msg), NULL);
        if (bytesReceived > 0) {
            msg[bytesReceived] = '\0';
            std::cout << msg << std::endl;
        }
        else if (bytesReceived == 0) {
            std::cout << "Connection closed by server." << std::endl;
            break; 
        }
        else {
            std::cerr << "recv failed with error: " << WSAGetLastError() << std::endl;
            break; 
        }
    }
    closesocket(ConnectionClient);  
}

int main() {
    WSADATA wsaData;
    WORD DLLversion = MAKEWORD(2, 1);

    if (WSAStartup(DLLversion, &wsaData) != 0) {
        std::cout << "\n\n\t\t\t\tLibrary not installed\n\n";
        exit(1);
    }

    SOCKADDR_IN addr;
    int sizeOfAddr = sizeof(addr);

    addr.sin_addr.s_addr = inet_addr("93.170.69.112");
    addr.sin_port = htons(1111);
    addr.sin_family = AF_INET;



    ConnectionClient = socket(AF_INET, SOCK_STREAM, NULL);
    if (ConnectionClient == INVALID_SOCKET) {
        std::cerr << "Socket creation failed: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }
    while (connect(ConnectionClient, (SOCKADDR*)&addr, sizeOfAddr) == SOCKET_ERROR) {
        std::cout << "Failed connection with error: " << WSAGetLastError() << std::endl;
        Sleep(3000);
    }
    std::cout << "\n\n\t\t\t\tSucces connected\n\n";

    std::thread threadOfMsgAccept(msgAccept);
    threadOfMsgAccept.detach();

    char msg[256];
    while (true) {
        std::cin.getline(msg, sizeof(msg)); 
        int msgLength = strlen(msg);
        if (msgLength > 0) {
            send(ConnectionClient, msg, msgLength, NULL);  
        }
    }
    return 0;
}

Спасибо вам заранее!
  • Вопрос задан
  • 63 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы