mardi 17 octobre 2023

How may I use the send and recv functions from an external source file? [closed]

I have an application that uses WindowsSockets to make connections and send data between server and client. I want to make those send and recv functions come from another source file in the project.   I want the send function to send what ever I tell it to send, and the recv function to return into a variable what the other pc send to me.

This is my server code:

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

#include <iostream>

#include "../headers_externos/conection.h"
#include "../headers_externos/data_module.h"

// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "8080"

int conectar()
{
    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;


    std::cout << "Inicializando a biblioteca de Winsock" << std::endl;
    // Inicializando a biblioteca de Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        std::cout << "WSASturtup falhou! Erro: " << iResult << std::endl;
        return 1;
    }
    std::cout << "Biblioteca inicializada com sucesso" << std::endl;

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    std::cout << "Resolvendo endereco e porta do servidor..." << std::endl;
    // Resolvendo o endereco e porta do servidor
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        std::cout << "getaddrinfo failed with error: %d\n" << iResult << std::endl;
        WSACleanup();
        return 1;
    }std::cout << " Sucesso!\n" << std::endl;


    std::cout << "Criando SOCKET para conexao..." << std::endl;
    // Criando Socket
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        std::cout << "Socket falhou! Erro: %ld\n\n" << WSAGetLastError() << std::endl;
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }
    std::cout << " Socket criado com sucesso!\n" << std::endl;

    std::cout << " Setando TCP listening socket...\n\n" << std::endl;
    std::cout << " bind()..." << std::endl;
    // Setup TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
            std::cout << " bind() falhou! Erro: %d\n\n" << WSAGetLastError() << std::endl;
            freeaddrinfo(result);
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    std::cout << " Sucesso!\n" << std::endl;

    freeaddrinfo(result);

    std::cout << " listen()..." << std::endl;
    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
           std::cout << " listen() falhou! Erro: %d\n\n" << WSAGetLastError()<< std::endl;
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    std::cout << " Sucesso!\n" << std::endl;

    std::cout << " Aguardando conexoes! accept()..." << std::endl;
    // Aceitando um cliente socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
           std::cout << " accept() falhou! Erro: %d\n\n"<< WSAGetLastError() << std::endl;
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    std::cout << " Sucesso!\n" << std::endl;

    closesocket(ListenSocket);

   std::cout << " Servidor pronto para receber dados!!!" << std::endl;
    // Recebe ate o cliente encerrar a conexao
    do {

        std::cout << " Aguardando..." << std::endl;

        
        /*
        RECIVE FUNCTION:
        */
          
        char *recvbuf = receber(ClientSocket);
        //--------------------------------------------

        if (iResult > 0) {
           std::cout << " Bytes recebidos: " << iResult << std::endl;
            std::cout << " Enviando um eco ao cliente..." << std::endl;
            // Echo the buffer back to the sender
            
            
            
           /*
            SEND FUNCTION:
            */
            iSendResult = enviar(ClientSocket, recvbuf);
            //-----------------------------------------
            
            
            
            
            if (iSendResult == SOCKET_ERROR) {
               std::cout << " send() falhou! Erro: " << WSAGetLastError() << std::endl;
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
            std::cout << " Sucesso! Bytes enviados: " << iSendResult << std::endl;
        }
        else if (iResult == 0)
            std::cout << " Conexao fexada pelo cliente!" << std::endl;
        else  {
           std::cout << " recv() falhou! Erro: " << WSAGetLastError()  << std::endl;
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }

    } while (iResult > 0);

    std::cout << " Encerrando..." << std::endl;
    // Fexando a conexao quando terminarmos
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
            std::cout << "shutdown() falhou! Erro:" << WSAGetLastError() << std::endl;
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
    }
    std::cout << " Encerrado!\n" << std::endl;
    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    return 0;

}

The functions send and recv should come from this script:

#include <winsock2.h>
#include "../headers_externos/data_module.h"

#define DEFAULT_BUFLEN 512


int enviar(SOCKET sock, const char* data)
{

send( sock, data, 0, 0 );

return 0;
}

char *receber(SOCKET socket)

{
    int recvbuflen = DEFAULT_BUFLEN;
    char *recvbuf = (char*)malloc(recvbuflen);

    recv(socket, recvbuf, recvbuflen, 0);

     return recvbuf;

     free(recvbuf);
}

The original cone is taken from here: https://pt.stackoverflow.com/questions/22719/cliente-servidor-windows-com-sockets-em-c

Aucun commentaire:

Enregistrer un commentaire