dqajyxqem115006813 2018-01-24 02:17
浏览 29

制作一个goroutine /通道以在没有可用连接时丢弃数据

I'm new to goroutines and trying to work out the idiomatic way to organise this code. My program will generate async status events that I want to transmit to a server over a websocket. Right now I have a global channel messagesToServer to receive the status messages. The idea is it that will send the data if we currently have a websocket open, or quietly drop it if the connection to the server is currently closed or unavailable.

Relevant snippets are below. I don't really like the non-blocking send - if for some reason my writer goroutine took a while to process a message I think it could end up dropping a quick second message for no reason?

But if I use a blocking send, sendStatusToServer could block something that shouldn't be blocked if the connection is offline. I could try to track connected/disconnected state but if a message was sent at the same time as the disconnection occurred I think there would be a race condition.

Is there a tidy way I can write this?

var (
    messagesToServer chan common.StationStatus
)

// ...
func sendStatusToServer(msg common.StationStatus) {
    // Must be non-blocking in case we're not connected
    select {
    case messagesToServer <- msg:
        break
    default:
        break
    }
}
// ...

// after making websocket connection
            log.Println("Connected to central server");
            finished := make(chan struct{})

            // Writer
            go func() {
                for {
                    select {
                    case msg := <-messagesToServer:
                        var buff bytes.Buffer
                        enc := gob.NewEncoder(&buff)
                        err = enc.Encode(msg)
                        conn.WriteMessage(websocket.BinaryMessage, buff.Bytes()); // ignore errors by design
                    case <-finished:
                        return;
                    }
                }
            }()

            // Reader as busy loop on this goroutine
            for {
                messageType, p, err := conn.ReadMessage()
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!