Reputation:
i'm trying to send bytes of image data via gorilla/websocket, my current code is :
var b bytes.Buffer
empty := bufio.NewWriter(&b)
png.Encode(empty, img)
err = c.WriteMessage(websocket.TextMessage, b.Bytes())
my code for receiving message :
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
// log.Printf("recv: %s", message)
ioutil.WriteFile("./nani.png", []byte(message), 0644)
then the saved file are corrupted, how do i write/read message as binary/bytes
Upvotes: 1
Views: 2899
Reputation: 120960
The bufio.Writer must be flushed to write any buffered data to the underlying writer (the bytes.Buffer in this case). If the bufio.Writer is not flushed, then some of the image data may be lost and the image will appear to be corrupted.
See the bufio.Writer documentation for more information on flushing the writer.
Here's the fix:
var b bytes.Buffer
empty := bufio.NewWriter(&b)
png.Encode(empty, img)
empty.Flush() // <-- add this call
Because there's no need to buffer data when writing to a byte.Buffer, the code can be improved by eliminating the bufio.Writer:
var b bytes.Buffer
png.Encode(&b, img)
Use websocket.BinaryMessage to send binary messages. See the Data Message section of the documentation for more information on message types.
Upvotes: 1