gpt4 book ai didi

c++ - UDP 数据报按空格字符拆分

转载 作者:行者123 更新时间:2023-11-28 02:26:41 26 4
gpt4 key购买 nike

我正试图进入 SDLnet,我遇到了一个问题,我从客户端发送到服务器的任何 UDP 数据包都在空格字符上被分解。我看不出发生这种情况的任何原因,因为我没有明确地对这种行为进行编程 - 我实际上只是在发送一个字符串。

我使用的源代码是 online example on The Game Programming Wiki 的一部分

服务器

    printf("Fill the buffer\n>");
scanf("%s", (char *)p->data);

p->address.host = srvadd.host; /* Set the destination host */
p->address.port = srvadd.port; /* And destination port */

p->len = strlen((char *)p->data) + 1;
SDLNet_UDP_Send(sd, -1, p); /* This sets the p->channel */

/* Quit if packet contains "quit" */
if (!strcmp((char *)p->data, "quit"))
quit = 1;

客户端

    /* Wait a packet. UDP_Recv returns != 0 if a packet is coming */
if (SDLNet_UDP_Recv(sd, p))
{
printf("UDP Packet incoming\n");
printf("\tChan: %d\n", p->channel);
printf("\tData: %s\n", (char *)p->data);
printf("\tLen: %d\n", p->len);
printf("\tMaxlen: %d\n", p->maxlen);
printf("\tStatus: %d\n", p->status);
printf("\tAddress: %x %x\n", p->address.host, p->address.port);

/* Quit if packet contains "quit" */
if (strcmp((char *)p->data, "quit") == 0)
quit = 1;
}

输出

输出看起来像this image .

我运行的操作系统是 Windows 7 64 位,我想知道这是否与操作系统有关。

最佳答案

这不是 UDP 的错,它与 char* 在使用 scanf 时被分割有关。 (我不是 100% 确定这里的细节。)但作为一般规则,在 C 中,you shouldn't use scanf

因为您正在使用 C++(至少根据标签),您应该使用 C++ 方式:

std::string msg = "";
std::cout << "Type a message and hit enter\n";

// Let user type a message
std::cin.ignore();
std::getline(std::cin, msg );

// UDPpacket uses Uint8, whereas msg.c_str() gives us a char*
// This simply copies the integer value of the chars into packet->data
memcpy(packet->data, msg.c_str(), msg.length() );

packet->len = msg.length();

注意:std::cin.ignore(); 用于确保我们停止并等待用户输入消息。

关于c++ - UDP 数据报按空格字符拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30402923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com