I have seen multiple applications write their data first to buffer, then writing that buffer to socket and not just directly to socket.
I have two questions:
Why is that?
If writing straight to socket is reasonable, then: How can I make socket wait for more data (We are dealing here with microseconds/nanoseconds delay) or how can I explicitly tell socket to send (not write to internal buffer) data. Right now kernel is sending each byte I write in seperate packet which is obviously not optimal ;)
I'm making my app in Go, here net.Conn implements io.Writer and it just makes sense to create utility functions that take 2 arguments: writer itself and data being written, so at the end I can just type that and be happy:
packets.WriteUint8(conn, 0x0)
I know that in many languages Buffers have their own utility methods for writing/reading structures, but what if I wanted to try above approach specifically in Go? I've tried finding similar questions, but failed. Info: App is meant to run on Linux
CodePudding user response:
Applications buffer writes to a network connection because a single write call with a large buffer is more efficient than multiple write calls with small buffers.
Call SetNoDelay(false) to make the operating system delay packet transmission with the hope of reducing the number of packets.
There is no option to explicitly flush a TCP connection’s buffer.
Before writing your own utilities, take a look at the bufio.Writer type. Many applications use this type to buffer writes to TCP connections and files.