How to read the exact bytes sent?

After creating a couple of hosts, and an stream that connects them, from host A I’m sending the following data:

func WriteData(bytes []byte, s network.Stream) {
	w := bufio.NewWriter(s)
	fmt.Printf("writing data; num bytes %v\n", len(bytes))
	w.Write(bytes)
	w.Flush()
	fmt.Printf("flushed data\n")
}

On the receiving side (host B) I’m reading using the following code:

func readData(r *bufio.Reader) {
	for {
		msg := make([]byte, r.Size()) // r.Size() is just the size of the buffer not of the total payload
		num, err := r.Read(msg) // after finishing 33 rounds of the for loop it blocks here
		if err != nil {
			fmt.Println("Error reading data:", err)
			return
		}
	}
}

I don’t know how to detect the end of the message, I know on the sending end the number of bytes but I cannot find them on the receiving end. Is there a standard protocol that will achieve something like:

  1. host A sends x bytes to host B
  2. host B reads x bytes from host A

Thanks

Hi,
I have faced with similar problem a few days ago, and solve my problem with adding s.CloseWrite() call to notify reader side to read all. Hope can solve your issue too.