我如何在Go中刷新tcp套接字?

问题描述 投票:0回答:1

如何在Go中刷新tcp套接字?

我一次在套接字上发送一条消息,向客户端指示进度,但是消息被捆绑在一起,并且所有消息都同时发送。我在任何地方都看不到冲洗功能。

如果Go不会公开此内容,我可以深入到地狱深处自己刷新底层缓冲区/套接字吗?

go tcp flush
1个回答
0
投票

正如@JimB所提到的,您不能Flush()一个net.Conn,因此,如果您的数据流不连续,它将被缓冲在其他位置。

如果您-或您的数据流中的中间包-正在使用例如bufio

w := bufio.NewWriter(conn)

if _, err := w.WriteString(msg); err != nil {
   return err
}

w.Flush()

conn不能刷新,bufio.Writer可以。

但是,如果您的连接是作为纯io.Writer类型(即仅Write()方法-无Flush())提供的,则可以尝试运行时转换/检查它是否“可刷新”:] >

// var connWriter io.Writer

type Flusher interface {
    // Flush sends any buffered data to the client.
    Flush() error
}

flushable, ok := connWriter.(Flusher) // runtime interface/type check

if !ok {
    log.Println("flushing not supported")
    return
}

flushable.Flush()
© www.soinside.com 2019 - 2024. All rights reserved.