c++ - 来自 UDP 连接的第一个缓冲区包含垃圾 - 后续连接正常

标签 c++ sockets

真的会尽量避免在这里发布我的整个项目 - 除非需要 :) 我有一个正在编写的客户端/服务器程序,客户端通过 UDP 端口与服务器联系,并希望收到格式为 "@7777~15~3701" 的数据包 - 第一次我连接,缓冲区中有垃圾。但是,一旦客户端退出,我再次启动它,下一个缓冲区 "@7777~15~3702" 就可以正常通过了。

int
RoutingManager::SendMessage(struct sockaddr_in toNode, char buffer[1024])
{
    #if logging > 1
        cout << "Sending: " << buffer << endl;
    #endif

    int n;
    unsigned int length = sizeof(struct sockaddr_in);
    //buffer = "@7777~15~3702"
    n = sendto(mySocket, buffer, strlen(buffer),0,
                (const struct sockaddr *)&toNode,length);

    if (n < strlen(buffer))
        perror("Sendto");

    cout << "Sent: " << n << " bytes of data\n";
}

.. 我在这里传递的缓冲区是从生成的:

//FIXED: This was the source of my issue it appears - a corrected
//implementation of this method has been included at the bottom.
char*
RoutingManager::GenerateConnectionString(struct Node n)
{
    char buffer[512];
    bzero(buffer,512);
    sprintf(buffer, "@7777~15~%d", n.id);
    cout << MYPORT << endl;
    return buffer;
}

服务器输出:

Sending: @7777~15~3701
Sent: 1 bytes of data
Waiting for nodes...

客户端:

RoutingNode::GetMyID()
{
    int n;
    char buffer[256];
    bzero(buffer,256);
    unsigned int length = sizeof(struct sockaddr_in);
    struct sockaddr_in from;

    n = sendto(mySocket,"!", strlen("!"),0,(const struct sockaddr *)&server,length);

    if (n < 0) 
        perror("Sendto");

    //once we have our information from the manager, let's hog some cpu
        //remove this crap when stuff gets more reliable
        fcntl(mySocket, F_SETFL, O_NONBLOCK);

    while(buffer[0] != '@')
        n = recvfrom(mySocket,buffer,256,0,(struct sockaddr *)&from, &length);

    if (n < 0) 
        perror("recvfrom");

    parser.ParseMessage(buffer, fromNode, messages);
}

当我解析消息时:

bool
RoutingMessage::ParseMessage(char* buffer, int &fromNode, map<int, string> &messages, const int MAX_CHARS_PER_LINE, 
                                const int MAX_TOKENS_PER_LINE, const char* const DELIMITER)
{
    #if logging > 1
        cout << "Buffer: " << buffer << endl;
    #endif

    if (buffer[0] != '@')
    {
        perror("Buffer malformated!");
        return false;
    }

    //remove the '@'
    buffer++;

    char buf[MAX_CHARS_PER_LINE];
    strcpy(buf, buffer);
    char* temp = strtok(buf, DELIMITER);
    if (temp == NULL)
    {
        perror("Buffer malformated!");
        return false;
    }

    fromNode = atoi(temp);
    temp = strtok(NULL, DELIMITER);

    vector<string> tokens;
    while(temp != NULL)
    {
        string val(temp);
        tokens.push_back(val);
        temp = strtok(NULL, DELIMITER);
    }

    //store messages in the map: <message-type>, <message>
    for (int i = 0; i < tokens.size(); i+=2)
        messages.insert(pair<int, string>(atoi(tokens[i].c_str()), tokens[i+1]));

    //all good
    return true;
}

然后输出结果,我得到了垃圾:

Buffer: <junk-symbol>
Buffer malformated!: Success
Node: 0

但是当客户端断开连接并且我重新启动相同的可执行文件时,我得到:

Buffer: @7777~15~3702
Node: 7777
Message Type: 15 Message: 3702

如我所料。有人知道我可以检查的内容吗?

更正方法--

void
RoutingManager::GenerateConnectionString(struct Node n, char* buffer)
{
    bzero(buffer,512);
    sprintf(buffer, "@7777~15~%d", n.id);
}

以上似乎解决了我的问题。

最佳答案

问题似乎出在 GenerateConnectionString() 函数中:

char*
RoutingManager::GenerateConnectionString(struct Node n)
{
    char buffer[512];
    ....
    return buffer;
}

它返回一个指向局部变量的指针。 所以返回的指针指向栈。因此,稍后当程序使用该区域的堆栈时,数据将被破坏。

关于c++ - 来自 UDP 连接的第一个缓冲区包含垃圾 - 后续连接正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22317738/

相关文章:

c++ - 如何区分 sys/sockets.h 中的 bind() 和 std::bind?

c++ - 无法在Windows上使用mingw将sqlite3与c连接

php - 如何在 PHP 和 C++ 之间建立通信?

linux -/etc/resolv.conf 中指定的超时值会做什么?

c++ - CMake - 尝试构建项目时遇到 undefined reference

c++ - std::vector、构造函数、对象

sockets - 没有可用的缓冲区空间(tcp.cpp :69) when setting SNDBUF and RCVBUF ZeroMQ, golang,MacOSX

sockets - 套接字 : Incorrect lenght returned by read() function

c++ - 打印数组内容时的奇怪值

linux - 如何在 Python/Jython 中仅读取套接字中的最新数据和/或清空套接字