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

how to send message to server from main (winsock)?

本文关键字:服务器 消息 winsock main      更新时间:2023-10-16

我使用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: %dn", 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: %dn", WSAGetLastError());
            closesocket(m_socket);
            WSACleanup();
            return false;
        }
        printf("sending initial message to server!n");
        printf("Bytes Sent: %ldn", iResult);
iResult = recv(m_socket, recvbuf, DEFAULT_BUFLEN, 0);
if ( iResult > 0 )
    printf("Bytes received: %dn", iResult);
else if ( iResult == 0 )
    printf("Connection closedn");
else
    printf("recv failed with error: %dn", 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: %dn", 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: %dn", 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(): %ldn", 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 functionn");
            iResult = recv(m_clientSocket, recvbuf, recvbuflen, 0);
            if (iResult > 0) {
                printf("Bytes received: %dn", 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: %dn", WSAGetLastError());
                    closesocket(m_clientSocket);
                    WSACleanup();
                    return false;
                }
                printf("Bytes sent: %dn", iSendResult);
            } 
            else if (iResult == 0) {
                printf("Connection closing...n");
            }
            else {
                printf("recv failed: %dn", 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: %dn", 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: %dn", 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(): %ldn", 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: %dn", 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: %ldn", 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: %dn", WSAGetLastError());
            closesocket(m_listenSocket);
            WSACleanup();
            return false;
        }
        printf("accept client socket.n");
        return true;
    }

客户的主要:

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

谢谢!

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