我应该使用的文件描述符或流的读/写插座 [英] Should I use file descriptors or streams for reading/writing to sockets
问题描述
在一个插座已经设置,它是更好的做法是使用read(2)和write(2)套接字描述来电,或使用fdopen(3),然后使用标准输入输出与插座描述一个流关联( 3)功能?
After a socket has been setup, is it better practice to use read(2) and write(2) calls on the socket descriptor, or to associate a stream with the socket descriptor using fdopen(3) and then use stdio(3) functions?
int sfd = socket(PF_INET, SOCK_STREAM, 0);
// setup the socket using sfd
FILE * stream = fdopen(sfd, "r+");
// use fprintf, fscanf, etc
编辑:我也无缓冲流
I also unbuffer the stream
setbuf(stream, NULL)
要避免在评论中提到刷新它。
To avoid having to flush it as mentioned in the comments.
我一直在使用这种方法,因为它让我重新使用FILE *流书面code和我有能够使用格式字符串的优势。 GNU似乎在暗示这是一个好主意。
I've been using this approach because it lets me reuse code written for FILE* streams, and I have the advantage of being able to use format strings. GNU seems to be suggesting that this is a good idea.
的http://www.gnu.org/software/libc/manual/html_node/Streams-and-File-Descriptors.html
但是通常当我使用套接字见code,套接字描述符是用来代替所有操作流。是否有优势,使用较低级别的功能呢?
However usually when I see code using sockets, the socket descriptor is used instead of a stream for all operations. Is there an advantage to using the lower level functions?
推荐答案
如果您需要更多的precise控制和错误条件处理,使用读
和写
。如果你不这样做,和preFER的标准输入输出功能的便利性,然后使用 FILE *
包装。
If you need more precise control and handling of error conditions, use read
and write
. If you don't, and prefer the convenience of stdio functions, then use the FILE*
wrapper.
与使用的一个问题FILE *
包装是,你没有对数据如何以及何时实际写入到插座的控制。这可能会导致低效的网络利用率和过度延迟(由于Nagle算法延迟ACK交互),如果你不小心。
One problem with using a FILE *
wrapper is that you don't have control over how and when data is actually written to the socket. This can result in inefficient network utilization and excessive delays (due to Nagle's algorithm interacting with delayed ACK) if you're not careful.
我会建议使用读
和写
直接,如果这是一个高性能的互联网应用。
I would recommend using read
and write
directly if this is a high-performance Internet application.
这篇关于我应该使用的文件描述符或流的读/写插座的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!