且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用write()而不是send()写入套接字时的性能影响

更新时间:2022-10-23 20:09:52

应该没有区别。引用 man 2 send $ c>:


send() write()是标志的存在。使用零标志参数, send()等效于 write()


只要你不想为 send()指定和标志,就可以使用 write()


I am working on writing a network application in C++ on the Linux platform using the typical sockets API, and I am looking at 2 alternative ways of writing a byte array to a TCP stream: either by calling write(), or by calling send(). I know that, since this is Linux, the socket handle is simply a file descriptor, and therefore it is valid to perform read() and write() calls on the socket, however the sockets API also provides the send() and recv() functions to perform the same tasks.

I am therefore wondering if there is any particular reason to choose one class of functions over the other - are the send/recv functions optimized for network writing/reading, do they perform better, etc? Or is it really arbitrary which functions I use? Do read() and write() behave properly in all cases?

Thanks for any insights!

There should be no difference. Quoting from man 2 send:

The only difference between send() and write() is the presence of flags. With zero flags parameter, send() is equivalent to write().

So long as you don't want to specify and flags for send() you can use write() freely.