gpt4 book ai didi

C 从套接字读取直到换行

转载 作者:行者123 更新时间:2023-11-30 15:24:47 24 4
gpt4 key购买 nike

我正在尝试编写一个 TCP 服务器,只要收到一条消息(保证以“\n”结尾),它就会响应客户端。我看过其他帖子,如 this one似乎会查看每个单独的字符以查看它是否是新行,但这似乎违背了将数据读入缓冲区的目的。有没有更好的方法来实现这一目标?

最佳答案

另一种方法是自己处理缓冲,例如:

std::string nextCommand;

while(1)
{
char buf[1024];
int numBytesRead = recv(mySocket, buf, sizeof(buf), 0);
if (numBytesRead > 0)
{
for (int i=0; i<numBytesRead; i++)
{
char c = buf[i];
if (c == '\n')
{
if (nextCommand.length() > 0)
{
printf("Next command is [%s]\n", nextCommand.c_str());
nextCommand = "";
}
}
else nextCommand += c;
}
}
else
{
printf("Socket closed or socket error!\n");
break;
}
}

(请注意,为简单起见,我使用 C++ std::string 来保存示例代码中的数据;由于您使用的是 C,因此您需要找到另一种方法来存储传入的字符串。如果你可以保证最大命令长度,你可以只使用固定大小的字符数组和计数器变量;如果你需要处理无限的命令大小,那么你需要想出某种可以增长的数据结构必要的,例如通过使用 realloc() 动态分配更大的缓冲区或使用链接列表或其他东西)

关于C 从套接字读取直到换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28229991/

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