C++ & WINSOCK - Recv two struct & two messages

C++ & WINSOCK - Recv two struct & two messages

本文关键字:two struct messages WINSOCK C++ Recv      更新时间:2023-10-16

我尝试重新记录我发送的所有数据。

我发送这个:

wpisano = send(maindll_socket, (char *)"witam", sizeof("witam"), 0);
wpisano2 = send(maindll_socket, (char *)"Pozdrawiam", sizeof("Pozdrawiam"), 0);

和recv

unsigned __stdcall main_pipe_server(void* Args)
{
    Sleep(500);
    LRESULT uiMessage;
    char wiadomosc[512];
    char tmpbuff[1024];
    int bytesRecv = SOCKET_ERROR;
    while (true){
        bytesRecv = recv(mainmenu::getInstance().dll_clients[0], wiadomosc, sizeof(wiadomosc), 0);
        if (bytesRecv > 0){
            MessageBox(NULL, (LPCSTR) wiadomosc, "DONE", NULL);
            sprintf_s(tmpbuff, 1023, "%s = %d | %d", wiadomosc, strlen(wiadomosc),bytesRecv );
            OutputDebugString(tmpbuff);
        }
        Sleep(1000);
    }
//(...)
}

结果是

MessageBox-"witam"

调试:"witam=5|17"

那么,第二个消息在哪里

上面是一个简单的问题。但我尝试发送两个带有数据的消息(其中一个是结构的编号,第二个是结构):

    int id=STRUCT_INIT_NUM;
    struct ST_ConInitChar a;
    a = { "BeCareful", python_func.py_getCurrentHp(), python_func.py_getMaxHp(), python_func.py_getMaxSp(), python_func.py_getMaxSp(), python_func.py_getMoney() };
    DWORD wpisano,wpisano2 = 0;
    wpisano = send(maindll_socket,(char *) &id, sizeof(id), 0);
    wpisano2 = send(maindll_socket, (char *)&a, sizeof(a), 0);

和recv-但它不起作用:

    unsigned __stdcall main_pipe_server(void* Args)
{
    Sleep(500);
    LRESULT uiMessage;
    char wiadomosc[512];
    char tmpbuff[1024];
    int bytesRecv = SOCKET_ERROR;
    while (true){
        bytesRecv = recv(mainmenu::getInstance().dll_clients[0], wiadomosc, sizeof(wiadomosc), 0);
        if (bytesRecv > sizeof(int)){
            char * p = wiadomosc;
            int *pId = (int*)p;
            p += sizeof(*pId);
            if (*pId == STRUCT_INIT_NUM){
                ST_ConInitChar * a = (ST_ConInitChar *)p;
                if (sizeof(a) > 0 && strlen(wiadomosc) > 0){
                    MessageBox(NULL, (LPCSTR)a->name, (LPCSTR) "DONE", NULL); // crash my program
                }
            }
        }
        Sleep(1000);
    }
//(...)
}

在第一个示例中,您总共发送了17个字节,然后读取了512个字节。您的wiadomosc缓冲区最终接收到这两条消息。您只看到一条消息被显示,因为您在发送的数据中包含了null终止符,然后将接收的数据视为null终止字符串。字符串文字被实现为const char[],因此您可以有效地执行以下操作:

const char str1[] = "witam"; // "witam"
wpisano = send(maindll_socket, (char *)str1, sizeof(str1), 0); // sizeof = 6, not 5

如果您不希望数据以null终止,请使用strlen()而不是sizeof()

第二个示例不起作用,因为结构的name成员是指向结构本身中不包含的外部数据的指针。当你发送结构时,你发送的是指针本身,而不是它所指向的数据。在这种情况下,你不能按原样发送结构,你需要将其序列化为可传输的格式并发送,然后接收它并反序列化为有意义的结构。您不必对POD类型(如整数)执行此操作,但可以对指针(如字符串)执行此任务。我建议您先发送字符串的长度,然后再发送字符串的字符。这样,您可以先读取长度,分配足够的缓冲区,然后读取其中的字符