Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance impact of using write() instead of send() when writing to a socket

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!

like image 944
rmrobins Avatar asked Jul 08 '09 20:07

rmrobins


People also ask

What happens when you write to a socket?

It reads input from the user on the standard input stream, and then forwards that text to the echo server by writing the text to the socket. The server echoes the input back through the socket to the client. The client program reads and displays the data passed back to it from the server.

What is write function in socket programming?

Behavior for sockets: The write() function writes data from a buffer on a socket with descriptor fs. The socket must be a connected socket. This call writes up to N bytes of data. Parameter Description fs. The file or socket descriptor.

Can a socket be simultaneously read and written?

Sockets are full duplex, so you can read while you write and vice-versa. You'd have to worry if you had multiple writers, but this is not the case.

What is the difference between read () and recv ()?

The only difference between recv() and read(2) is the presence of flags. With a zero flags argument, recv() is generally equivalent to read(2) (but see NOTES).


1 Answers

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.

like image 190
Nathan Fellman Avatar answered Oct 20 '22 00:10

Nathan Fellman