1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thankyou for websocket.BinaryMessage constant; last question; i fail to save a valid file from message; the exact code are still same in question
@DEFFPALKON Did you fix the problem with the bufio.Writer as described in this answer?
i use the second code; and now i transfer json; not bin anymore @cerise-limon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.