C ++ Winsocks,recv(socket,512,0)一次仅接收一个字符

时间:2019-07-12 18:03:55

标签: c++ winsock

出于某些奇怪的原因,我初始化了套接字:

void init()
{
    cout << "\t\t-----TCP SERVER---" << endl;
    cout << endl;

    //STEP 1 WSAStartup
    iwsastartup = WSAStartup(MAKEWORD(2, 2), &Winsockdata);
    if (iwsastartup != 0){
        cout << "startup failed" << endl;
    }
    cout << "startup success" << endl;
    //STEP 2 fill structure
    TCPServerAdd.sin_family = AF_INET;
    TCPServerAdd.sin_addr.s_addr = inet_addr("127.0.0.1");
    TCPServerAdd.sin_port = htons(8000);

    //STEP 3 socket creation
    TCPServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (TCPServerSocket == INVALID_SOCKET){
        cout << "server socket creation failed: " << WSAGetLastError() << endl;
    }
    //STEP 4 binding
    iBind = ::bind(TCPServerSocket, (SOCKADDR*)&TCPServerAdd, sizeof(TCPServerAdd));
    if (iBind == SOCKET_ERROR){
        cout << "Binding failed: " << WSAGetLastError() << endl;
    }
    cout << "binding success" << endl;
    iListen = listen(TCPServerSocket, 2);
    //STEP 5 listening
    if (iListen == SOCKET_ERROR){
        cout << "listening failed: " << WSAGetLastError() << endl;
    }
    cout << "listening..." << endl;
    //STEP 6 accept
    sAcceptSocket = accept(TCPServerSocket, (SOCKADDR*)&TCPClientAdd, &iTCPClientAdd);
    if (sAcceptSocket == INVALID_SOCKET){
        cout << "accept failed: " << WSAGetLastError() << endl;
    }
    cout << "connection accepted" << endl;
}

其中Send和Recv缓冲区是const char [512],并且像这样接收和发送:

void recieve_(){
    while (true)
    {

        //STEP 7 recv data from client
        iRecv = recv(sAcceptSocket, RecvBuffer, iRecvBuffer, 0);
        if (iRecv == SOCKET_ERROR){
            cout << "recv failed: " << WSAGetLastError() << endl;
        }
        else{
            //cout << "recv:" << RecvBuffer << endl;
            MessageBox(nullptr, LPCWSTR(RecvBuffer), TEXT("Message"), MB_OK);
        }
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    init();
    //STEP 7 send data to client

    thread t1(recieve_);

    while (true){
        system("PAUSE");
        iSend = send(sAcceptSocket, SenderBuffer, iSenderBuffer, 0);
        if (iSend == SOCKET_ERROR){
            cout << "sending failed: " << WSAGetLastError() << endl;
        }
        else{
            cout << "sent successfully" << endl;
        }
    }
    //STEP 9 close socket
    iCloseSocket = closesocket(TCPServerSocket);
    closesocket(sAcceptSocket);
    WSACleanup();
    system("PAUSE");
    return 0;
}

即使在更简单的单线程版本中,缓冲区也只是发送的缓冲区的第一个字符,例如 char SendBuffer [512] =“你好”; 被接收为仅设置了元素0的512数组,这是配置问题吗?

任何帮助表示赞赏。

0 个答案:

没有答案