Search code examples
linuxsocketsbuffertcpserver

How does the socket buffer work in Linux?


I'm using python TCP server, and the clients will just send data to the server via sockets. In Linux, there are the buffer size defined for TCP. So does that mean when the client writes to the socket, the data will be buffered and return true directly? That means we don't really know whether the data will reach to the server. Is that correct?

If that's the case, is it a good practice to disable the buffering in Linux? What issue could be caused if it's disabled? Thanks


Solution

  • In Linux, there are the buffer size defined for TCP

    Every platform does that.

    So does that mean when the client writes to the socket, the data will be buffered and return true directly? That means we don't really know whether the data will reach to the server. Is that correct?

    Yes, and yes. The only way to know if the data actually reaches the server is to have the server send a reply back to the client, and for the client to receive and process that reply.

    If that's the case, is it a good practice to disable the buffering in Linux?

    No, and you can't disable it anyway, as it is core of how sockets interact with the OS kernel. All you can do is lower the buffer size if needed (but even then, the socket will enforce a minimum size of its choosing). Also, if you need to send many small packets in a short amount of time, you can enable the TCP_NODELAY option on the socket to avoid unwanted delays in flushing the buffer to the network.