直接写入套接字 vs 写入缓冲区

huangapple go评论88阅读模式
英文:

Writing directly to socket vs to buffer

问题

我看到多个应用程序将它们的数据首先写入缓冲区,然后再将该缓冲区写入套接字,而不是直接写入套接字

我有两个问题:

  • 为什么会这样?

  • 如果直接写入套接字是合理的,那么:我该如何使套接字等待更多数据(我们在这里处理微秒/纳秒级的延迟),或者我该如何显式地告诉套接字发送数据(而不是写入内部缓冲区)。目前内核会将我写入的每个字节都发送为单独的数据包,这显然不是最优的 直接写入套接字 vs 写入缓冲区

我正在使用Go编写我的应用程序,在这里net.Conn实现了io.Writer,创建一个接受两个参数(写入器本身和要写入的数据)的实用函数是有道理的,这样最后我只需键入以下内容就可以满意了:

packets.WriteUint8(conn, 0x0)

我知道在许多语言中,缓冲区都有自己的实用方法来写入/读取结构体,但如果我想特别在Go中尝试上述方法怎么办?我尝试寻找类似的问题,但没有成功。
信息:该应用程序旨在在Linux上运行。

英文:

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 直接写入套接字 vs 写入缓冲区

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

答案1

得分: 4

应用程序将写入网络连接的数据缓冲起来,因为使用一个具有大缓冲区的写入调用比使用多个具有小缓冲区的写入调用更高效。

调用SetNoDelay(false)可以使操作系统延迟数据包传输,以期减少数据包的数量。

没有明确刷新TCP连接缓冲区的选项。

在编写自己的实用程序之前,可以查看bufio.Writer类型。许多应用程序使用此类型来缓冲对TCP连接和文件的写入操作。

英文:

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.

huangapple
  • 本文由 发表于 2022年6月26日 20:46:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/72761735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定