简体   繁体   English

在C ++模式下从套接字读取套接字的所有可用字节的最佳方法

[英]Best way of reading all available bytes from socket in blocking mode, C++

What is the best way of reading from blocking socket all available bytes? 从阻塞套接字读取所有可用字节的最佳方法是什么? 'Available' means that server response is a bunch of text lines (each with '\\n') and EOF is a line with some prefix. “可用”表示服务器响应是一堆文本行(每行都带有“ \\ n”),而EOF是带有某些前缀的行。 Length of this response is always different, so I don't know it before reading. 该响应的长度总是不同的,因此在阅读之前我不知道。 I assume using select() ( poll , epoll ) and then 'ioctl(FIONREAD)' is the best way, am I right? 我假设使用select()pollepoll ),然后使用'ioctl(FIONREAD)'是最好的方法,对吗? Or may be just reading all available at that moment, then checking if EOF is reached and if not, then repeating all again? 还是只是在读取当时所有可用的内容,然后检查是否达到了EOF,如果没有达到,则再次重复所有操作? Yes, it sounds more rational. 是的,听起来更合理。 Does it all make any sense? 这一切有意义吗? So, what is the most efficient way? 那么,最有效的方法是什么?

If you are doing blocking reads there is little point in using select / epoll . 如果您要进行阻塞读取,那么使用select / epoll毫无意义。

ioctl(FIONREAD) is a pretty useless call because by the time it returns more data may have arrived into the kernel socket buffer. ioctl(FIONREAD)是一个非常无用的调用,因为到它返回更多数据时,它可能已经到达内核套接字缓冲区。

Blocking reads are easy: just keep read ing into your user-space socket buffer until the message terminator is found. 阻止读取很容易:只要继续read用户空间套接字缓冲区,直到找到消息终止符即可。

Ideally, the networking components you use should not care whether the socket is in blocking or in non-blocking mode: there should be a function that is called when the socket is ready for reading. 理想情况下,您使用的网络组件不应该关心套接字是处于阻塞模式还是非阻塞模式:当套接字准备好读取时,应该调用一个函数。 In blocking mode you would call this function regardless of whether the socket is ready, it just blocks on read if no data is available. 在阻塞模式下,无论套接字是否准备就绪,都将调用此函数,如果没有可用数据,它将在read时阻塞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM