如何从套接字读取并返回单独的行?
我是否应该读取每个字符,直到它到达 \n 字符,将它们全部连接在一起并返回,或者是否有更好的方法?我应该使用 std::string 还是 char 来实现此目的?
我尝试了以下两个示例,但我需要将它们作为单独的行来读取
示例 1:
std::string sockread()
{
std::string s;
s.resize(DEFAULT_BUFLEN);
int result = recv(m_socket, &s[0], DEFAULT_BUFLEN, 0);
if (result > 0) {
return s;
} else if (result == 0) {
connected = false;
} else {
std::cout << "recv failed with error " << WSAGetLastError() << "\n";
}
throw std::runtime_error("Socket connection failed!");
}
示例 2:
char sockread(void)
{
int result;
char buffer[DEFAULT_BUFLEN];
result = recv(m_socket, buffer, DEFAULT_BUFLEN, 0);
if (result > 0) {
return *buffer;
}
else if (result == 0)
{
connected = false;
return *buffer;
}
else {
printf("recv failed with error: %d\n", WSAGetLastError());
return *buffer;
}
}
Am I supposed to read each character until it reaches the \n character, join them all together and return or is there a better way? Should I use std::string or char for this?
I tried the following two examples but I need to read them as separate lines
Example 1:
std::string sockread()
{
std::string s;
s.resize(DEFAULT_BUFLEN);
int result = recv(m_socket, &s[0], DEFAULT_BUFLEN, 0);
if (result > 0) {
return s;
} else if (result == 0) {
connected = false;
} else {
std::cout << "recv failed with error " << WSAGetLastError() << "\n";
}
throw std::runtime_error("Socket connection failed!");
}
Example 2:
char sockread(void)
{
int result;
char buffer[DEFAULT_BUFLEN];
result = recv(m_socket, buffer, DEFAULT_BUFLEN, 0);
if (result > 0) {
return *buffer;
}
else if (result == 0)
{
connected = false;
return *buffer;
}
else {
printf("recv failed with error: %d\n", WSAGetLastError());
return *buffer;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有几个选择,具体取决于套接字代码的其余部分的布局方式。
从编码的角度来看,最简单的方法是一次只读取 1 个字符,直到遇到要查找的字符。从性能角度来看,这不是最好的方法,尽管您可以使用本地缓冲区来帮助您至少避免内存碎片,例如:
另一方面,将原始套接字数据读入中间缓冲区,其余的读取功能将在中间缓冲区中进行需要时访问可以更有效地读取套接字,以便更快地从套接字缓冲区中获取数据(减少另一端的阻塞),例如:
You have a few options, depending on how the rest of your socket code is laid out.
The simpliest approach, from a coding perspective, is to just read 1 char at a time until you encounter the char you are looking for. This is not the best approach from a performance perspective, though you can use a local buffer to help you avoid fragmenting memory at least, eg:
On the other hand, reading the raw socket data into an intermediate buffer that the rest of your reading functions access when needed allows for more efficient reading of the socket so the data is gotten out of the socket's buffers quicker (causing less blocking on the other side), eg:
使用Boost.ASIO - 基于行的操作这里。
Use Boost.ASIO - line-based operations covered here.