Gorilla websockets, multiple messages in one event

Viewed 995

I am using the chat app example from gorilla websockets, but I have an issue, sometimes, when the backend needs to send two different messages to the client, they are send in just one Message Event, this is bad for me because JSON.parse will fail parsing 2 jsons from one string. I can do a split by newline and get every json from the message, but I prefer not to.
If I put a timeout on backend everything works.
Can I do something to prevent this? If not can you please explain me why?

This is the chat example: https://github.com/gorilla/websocket/tree/master/examples/chat

This is my code where I broadcast 2 messages:

if err == nil {
    c.SendMessageWithOrders(DB)
    data := models.EventSuccess{
        Event: utils.EventOrdersCreateSuccess,
    }
    toReturnBytes, err := json.Marshal(data)
    if err == nil {
    toReturn := BroadcastOne{
        ID:      c.ID,
        Message: toReturnBytes,
    }
    NewHub.broadcastOne <- &toReturn
    }
}

c.SendMessageWithOrders(DB) Is making NewHub.broadcastOne <- &toReturn with different data

1 Answers

The following code in client.go reduces the amount of data sent over the network by sending queued chat messages as a single WebSocket message:

        n := len(c.send)
        for i := 0; i < n; i++ {
            w.Write(newline)
            w.Write(<-c.send)
        }

Fix the problem by deleting the code from the example. The optimization is not required.

Related