GionJh
GionJh

Reputation: 2884

Socket and buffers

I know standard c library functions fwrite and fread are a sort buffering wrappers of write and read system calls, buffers are used for performance reasons I totally understand. what I don't understand is the role of buffers in socket programming functions write and read. can you help me understand what they are used for, highlighting differences and similarities with files buffers?

I'm a newbie in socket programming...

Upvotes: 1

Views: 493

Answers (2)

Karoly Horvath
Karoly Horvath

Reputation: 96258

When the kernel receives packets it has to put those data somewhere. It stores it in the buffer. When your app does the next read it can fetch the data from those buffers. If you have a UDP connection and your app doesn't read those buffers it gets full and the kernel starts to drop the received packets. If you have a TCP connection it will acknowledge the packets as long as there is free space in the buffers, but after that it will signal that it cannot read more.

Write buffers are necessary because the network interface is a scarce resource, the kernel typically cannot send immediately a packet. If you do a big write() it could be chopped up to hundreds of packets. So the kernel will store that data in the buffers. The buffer also does a good job if you do a lot of small writes, see Nagle's algorithm.

Upvotes: 3

corsiKa
corsiKa

Reputation: 82559

Imagine if you sent your information one byte at a time. You'd be generating a 100 byte packet to send 1 byte, and if it's a TCP connection, depending in implementation, waiting until you got a syn/ack before sending more? Sounds pretty inefficient to me.

Instead, you use a buffer to store up a large amount of data and send that across in a single packet, just like storing up data before writing to disk.

Upvotes: 2

Related Questions