简体   繁体   English

如何冲洗 Go 中的 tcp 插座?

[英]How do I flush a tcp socket in Go?

How do I flush a tcp socket in Go?如何冲洗 Go 中的 tcp 插座?

I'm sending messages one at a time down a socket, indicating progress to a client, but the messages get bunched up and all sent at the same time.我正在通过套接字一次发送一条消息,向客户端指示进度,但是这些消息会聚集在一起并同时发送。 I can't see a flush function anywhere.我在任何地方都看不到齐平的 function。

The messages are sent a couple of seconds apart, they're <100bytes each, and I'm sending them to localhost.消息间隔几秒钟发送,每个消息<100字节,我将它们发送到本地主机。 By flushing, I mean I want to clear any buffers stopping them from getting out on the wire;通过冲洗,我的意思是我想清除任何阻止它们从电线上出来的缓冲区; they're clearly being buffered somewhere in this case.在这种情况下,它们显然在某处被缓冲。

If Go doesn't expose this, can I reach down into the depths of hell to flush the underlying buffer/socket myself?如果 Go 没有暴露这一点,我可以深入到地狱深处自己刷新底层缓冲区/套接字吗?

As @JimB mentioned you can't Flush() a net.Conn , so if your data-flow is stuttering, it is being buffered elsewhere.正如@JimB 提到的,你不能Flush() a net.Conn ,所以如果你的数据流口吃,它会在其他地方缓冲。

If you - or an intermediate package in your data-flow - is using for example bufio :如果您 - 或数据流中的中间 package - 正在使用例如bufio

w := bufio.NewWriter(conn)

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

w.Flush()

while the conn cannot be flushed, the bufio.Writer can.虽然无法刷新conn ,但bufio.Writer可以。

If, however, your connection is given to you as a pure io.Writer type (ie Write() method only - no Flush() ) you may try a runtime conversion/check to see if it is "flushable":但是,如果您的连接是纯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()

Argh.啊。 It was being buffered client-side in a bash pipe.它在 bash 管道中被客户端缓冲。 Removed the | ts -s '%.T'删除了| ts -s '%.T' | ts -s '%.T' which I had to try to measure the time elapsed between responses, and now it works. | ts -s '%.T'我不得不尝试测量响应之间经过的时间,现在它可以工作了。

brew install expect and unbuffer my-command -a -b --foo | ts -s '%.T' brew install expectunbuffer my-command -a -b --foo | ts -s '%.T' unbuffer my-command -a -b --foo | ts -s '%.T' to work around this on mac, linux suggestions here https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe unbuffer my-command -a -b --foo | ts -s '%.T'在 mac 上解决这个问题,linux 建议在这里https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe

Leaving the question open since I got a good answer on the question I posed, which might help others.留下问题,因为我对我提出的问题有一个很好的答案,这可能对其他人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM