Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何从main(winsock)向服务器发送消息?_C++_Client_Server_Winsock_Messages - Fatal编程技术网

C++ 如何从main(winsock)向服务器发送消息?

C++ 如何从main(winsock)向服务器发送消息?,c++,client,server,winsock,messages,C++,Client,Server,Winsock,Messages,我使用winsock创建了一个简单的客户机-服务器应用程序。 我想向服务器发送消息,作为对用户输入的响应,但它不起作用。 我创建了一个函数sendData(),它向服务器发送“test”。 如果我在连接服务器后立即调用func,它可以正常工作,但是如果我从main或其他类调用它,服务器将不接受该消息 有什么建议吗 客户端代码: #include "StdAfx.h" #include "CommHandler.h" #define DEFAULT_PORT "27015

我使用winsock创建了一个简单的客户机-服务器应用程序。 我想向服务器发送消息,作为对用户输入的响应,但它不起作用。 我创建了一个函数sendData(),它向服务器发送“test”。 如果我在连接服务器后立即调用func,它可以正常工作,但是如果我从main或其他类调用它,服务器将不接受该消息

有什么建议吗

客户端代码:

    #include "StdAfx.h"
    #include "CommHandler.h"

    #define DEFAULT_PORT "27015"
    #define DEFAULT_BUFLEN 512

    SOCKET CommHandler::m_socket = INVALID_SOCKET;

    CommHandler::CommHandler(void)
    {
        init();
    }
    //===============================================================
    CommHandler::~CommHandler(void)
    {
        // cleanup
        closesocket(m_socket);
        WSACleanup();
    }
    //===============================================================
    bool CommHandler::init()
    {
        return (establishConnection("127.0.0.1"));
    }
    //===============================================================
    bool CommHandler::sendData()
    {
        if (m_socket == INVALID_SOCKET) {
            printf("send msg failed; INVALID_SOCKET: %d\n", WSAGetLastError());
            return false;
        }

        int recvbuflen = DEFAULT_BUFLEN;
        char *sendbuf = "this is a test";
        char recvbuf[DEFAULT_BUFLEN];

        // Send an initial buffer
        int iResult = send(m_socket, sendbuf, (int) strlen(sendbuf), 0);
        if (iResult == SOCKET_ERROR) {
            printf("send failed: %d\n", WSAGetLastError());
            closesocket(m_socket);
            WSACleanup();
            return false;
        }

        printf("sending initial message to server!\n");
        printf("Bytes Sent: %ld\n", iResult);

iResult = recv(m_socket, recvbuf, DEFAULT_BUFLEN, 0);
if ( iResult > 0 )
    printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
    printf("Connection closed\n");
else
    printf("recv failed with error: %d\n", WSAGetLastError());
return true;
    }
    //===============================================================
    bool  CommHandler::establishConnection(const std::string ip)
    {
        return (initWinsock() && createSocket(ip));
    }
    //===============================================================
    bool CommHandler::initWinsock()
    {
        // Initialize Winsock
        int iResult = WSAStartup(MAKEWORD(2,2), &m_wsaData);
        if (iResult != 0) {
    printf("WSAStartup failed: %d\n", iResult);
    return false;
}

printf("WSAStartup succeeded.\n");
return true;
    }
    //===============================================================
    bool CommHandler::createSocket(const std::string ip)
    {
        struct addrinfo *result = NULL,
            *ptr = NULL,
            hints;

ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

// Resolve the server address and port
int iResult = getaddrinfo(ip.c_str(), DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
    printf("getaddrinfo failed: %d\n", iResult);
    WSACleanup();
    return false;
}

// Attempt to connect to the first address returned by
// the call to getaddrinfo
ptr=result;

// Create a SOCKET for connecting to server
m_socket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);

if (m_socket == INVALID_SOCKET) {
    printf("Error at socket(): %ld\n", WSAGetLastError());
    freeaddrinfo(result);
    WSACleanup();
    return false;
}
printf("socket creation succeeded.\n");

// Connect to server.
iResult = connect( m_socket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
    closesocket(m_socket);
    m_socket = INVALID_SOCKET;
}

        freeaddrinfo(result);

        if (m_socket == INVALID_SOCKET) {
            printf("Unable to connect to server!\n");
            WSACleanup();
            return false;
        }

                printf("connected to server!\n");

        // Send an initial buffer
        sendData(); //this send data is received by the server
        sendData(); //this send data is received by the server

        return true;
    }
服务器代码:

    #include "StdAfx.h"
    #include "CommHandler.h"

    #define DEFAULT_PORT "27015"
    #define DEFAULT_BUFLEN 512

    CommHandler::CommHandler(void):m_listenSocket(INVALID_SOCKET),          m_clientSocket(INVALID_SOCKET)
    {
    }
    //===============================================================
    CommHandler::~CommHandler(void)
    {
    }
    //===============================================================
    bool CommHandler::init()
    {
        if (establishConnection()) {
            return (receiveData());
        }

        return false;
    }
    //===============================================================
    bool CommHandler::receiveData()
    {
        char recvbuf[DEFAULT_BUFLEN];
        int iResult, iSendResult;
        int recvbuflen = DEFAULT_BUFLEN;

        // Receive until the peer shuts down the connection
        do {
            printf("in receiveData function\n");
            iResult = recv(m_clientSocket, recvbuf, recvbuflen, 0);
            if (iResult > 0) {
                printf("Bytes received: %d\n", iResult);
                std::cout<<recvbuf<<std::endl;

                // Echo the buffer back to the sender
                iSendResult = send(m_clientSocket, recvbuf, iResult, 0);
                if (iSendResult == SOCKET_ERROR) {
                    printf("send failed: %d\n", WSAGetLastError());
                    closesocket(m_clientSocket);
                    WSACleanup();
                    return false;
                }
                printf("Bytes sent: %d\n", iSendResult);
            } 
            else if (iResult == 0) {
                printf("Connection closing...\n");
            }
            else {
                printf("recv failed: %d\n", WSAGetLastError());
                closesocket(m_clientSocket);
                WSACleanup();
                return false;
            }

        } while (iResult > 0);

        printf("exit receiveData function with no errors (finish while)\n");
        return true;
    }
    //===============================================================
    bool CommHandler::establishConnection()
    {
        // Initialize Winsock
        int iResult = WSAStartup(MAKEWORD(2,2), &m_wsaData);
        if (iResult != 0) {
            printf("WSAStartup failed: %d\n", iResult);
            return false;
        }

        printf("WSAStartup succeeded.\n");

        struct addrinfo *result = NULL, *ptr = NULL, hints;

        ZeroMemory(&hints, sizeof (hints));
        hints.ai_family     = AF_INET;      //used to specify the IPv4 address family
        hints.ai_socktype   = SOCK_STREAM;  //used to specify a stream socket
        hints.ai_protocol   = IPPROTO_TCP;  //used to specify the TCP protocol 
        hints.ai_flags      = AI_PASSIVE;

        // Resolve the local address and port to be used by the server
        int iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
        if (iResult != 0) {
            printf("getaddrinfo failed: %d\n", iResult);
            WSACleanup();
            return false;
        }

        // Create a SOCKET for the server to listen for client connections
        m_listenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

        if (m_listenSocket == INVALID_SOCKET) {
            printf("Error at socket(): %ld\n", WSAGetLastError());
            freeaddrinfo(result);
            WSACleanup();
            return false;
        }

        printf("socket creation succeeded.\n");

        //bind the socket:
        // Setup the TCP listening socket
        iResult = bind( m_listenSocket, result->ai_addr, (int)result->ai_addrlen);
        if (iResult == SOCKET_ERROR) {
            printf("bind failed with error: %d\n", WSAGetLastError());
            freeaddrinfo(result);
            closesocket(m_listenSocket);
            WSACleanup();
            return false;
        }

        freeaddrinfo(result);
        printf("bind the socket.\n");

        //listen the socket
        if ( listen( m_listenSocket, SOMAXCONN ) == SOCKET_ERROR ) {
            printf( "Listen failed with error: %ld\n", WSAGetLastError() );
            closesocket(m_listenSocket);
            WSACleanup();
            return false;
        }
        printf("listen the socket.\n");

        // Accept a client socket
        m_clientSocket = accept(m_listenSocket, NULL, NULL);
        if (m_clientSocket == INVALID_SOCKET) {
            printf("accept failed: %d\n", WSAGetLastError());
            closesocket(m_listenSocket);
            WSACleanup();
            return false;
        }

        printf("accept client socket.\n");
        return true;
    }

谢谢

我发现了问题。我调用了两次init()函数,它断开了连接:|

    int main()
    {
        CommHandler ch;
        if (!ch.init())
            return 1;
        ch.sendData(); //this msg isn't received by server !!!
        system("pause");
        return(0);
    }