如何在Go中丢弃连接中的任何传入数据?

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

How to discard any incoming data in a connection in Go?

问题

我正在向远程服务器发送一个请求,但不关心它的响应。我不想直接关闭连接,因为如果这样做,服务器会出现"Broken pipe"错误。

我目前使用一个缓冲区循环调用Read()方法:

con, _ := net.Dial("tcp", host)

// ...

data := make([]byte, 512)
for {
	if _, err = con.Read(data); err == io.EOF {
		break
	}
}

但我想要的是类似于Bash中的>/dev/null的效果。我找到了ioutils.Discard,但它是一个io.Writer,而con.Read只能在[]byte缓冲区上工作。

有没有比我目前做的读取缓冲区更高效的方法?

英文:

I’m sending a request to a remote server, but don’t care about its response. I don’t want to close the connection directly because the server gets a Broken pipe error if I do that.

I currently loop on Read() calls with a buffer:

con, _ := net.Dial("tcp", host)

// ...

data := make([]byte, 512)
for {
	if _, err = con.Read(data); err == io.EOF {
		break
	}
}

But I’m looking for something like >/dev/null in Bash. I’ve found ioutils.Discard, but it’s an io.Writer and con.Read only works on a []byte buffer.

Is there a more efficient way than just reading in a buffer like what I’m currently doing?

答案1

得分: 33

你需要像这样使用ioutil.Discard

io.Copy(ioutil.Discard, con)

io.Copy函数从源io.Reader复制到目标io.Writer

func Copy(dst Writer, src Reader) (written int64, err error)

io.Reader是一个接口,定义如下:

type Reader interface {
    Read(p []byte) (n int, err error)
}

io.Writer是一个接口,定义如下:

type Writer interface {
    Write(p []byte) (n int, err error)
}

net.Conn实现了io.Reader接口,而ioutil.Discard实现了io.Writer接口。

英文:

you have to use ioutil.Discard like this

io.Copy(ioutil.Discard, con)

io.Copy copies from a src io.Reader to a io.Writer

func Copy(dst Writer, src Reader) (written int64, err error)

io.Reader is an interface defined as

type Reader interface {
        Read(p []byte) (n int, err error)
}

io.Writer

type Writer interface {
        Write(p []byte) (n int, err error)
}

net.Conn implements io.Reader and ioutil.Discard implements io.Writer

答案2

得分: 9

自Go 1.16(2021年2月)起,程序应该使用io.Discard

package main

import (
   "fmt"
   "io"
)

func main() {
   fmt.Fprint(io.Discard, "hello world")
}

https://golang.org/pkg/io#Discard

英文:

Since Go 1.16 (Feb 2021), programs should be using io.Discard:

package main

import (
   "fmt"
   "io"
)

func main() {
   fmt.Fprint(io.Discard, "hello world")
}

https://golang.org/pkg/io#Discard

huangapple
  • 本文由 发表于 2014年7月12日 05:47:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/24707083.html
匿名

发表评论

匿名网友

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

确定