英文:
Golang - Hijack Arguments
问题
当使用http.ResponseWriter实例的Hijack()方法时,
> Hijack() (net.Conn, *bufio.ReadWriter, error)
从net.Conn和*bufio.ReadWriter读取有什么区别?
英文:
When using Hijack() with a http.ResponseWriter instance
> Hijack() (net.Conn, *bufio.ReadWriter, error)
What is the difference between reading from the net.Conn and the *bufio.ReadWriter?
答案1
得分: 5
net.Conn.Read和*bufio.ReadWriter.Read都从同一个连接中读取数据,但后者是有缓冲的。标准库中的"net/http"包中的Hijack方法直接返回了一个包装在bufio.ReadWriter中的net.Conn,并且使用了已经为HTTP请求分配的相同的*bufio.Reader。
在直接从网络连接中读取数据时,可能会有仍然在bufio.Reader中缓冲的数据,如果不注意可能会错过这些数据。如果你想直接使用net.Conn,你应该使用Reader.Buffered来检查是否已经有缓冲的数据,并根据使用的协议进行处理。
一般来说,你应该优先使用bufio.ReadWriter,因为它对于非最佳大小的读写操作会更高效。
net.Conn仍然需要用于处理读写超时,当完成操作时关闭net.Conn,以及其他任何与网络相关的活动。
英文:
net.Conn.Read and *bufio.ReadWriter.Read both read from the same connection, but the latter is buffered. The Hijack method in the standard "net/http" package directly returns the net.Conn wrapped in a bufio.ReadWriter, using the same *bufio.Reader that was already allocated for the http request.
It's possible that there is still data buffered in the bufio.Reader which you may miss when reading directly from the network connection. If you want to use the net.Conn directly, you should check if there is buffered data already with Reader.Buffered, and handle that according to the protocol being used.
In general, you should prefer to use bufio.ReadWriter, as it will be more efficient for non-optimally sized reads and writes to the network.
The net.Conn is still needed to handle the Read and Write deadlines, to close the net.Conn when you're done, and for any other network-specific activities.
答案2
得分: -1
它们的区别在于缓冲IO。
net.Conn实现了Read()和Write(),从而实现了io.Reader和io.Writer。这就是为什么bufio可以将其包装为缓冲的ReadWriter,并进一步使用这两种方法以缓冲的方式实现其他函数。
如果你只想使用Read()和Write(),可以直接使用net.Conn,否则你可以利用缓冲的ReadWriter方法。
请参阅https://golang.org/pkg/io/#Reader和https://golang.org/pkg/io/#Writer。
英文:
Their difference is buffered IO.
net.Conn implements Read() and Write() thus implementing io.Reader and io.Writer. This is why bufio can wrap it up as a buffered ReadWriter and further implement functions on top using those two methods in a buffered manner.
If you only want to use Read() and Write(), you can just stick with net.Conn, otherwise you can take advantage for the buffered ReadWriter methods.
See https://golang.org/pkg/io/#Reader and https://golang.org/pkg/io/#Writer
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论