On Wednesday, 31 March 2021 at 04:13:12 UTC+1 matt....@gmail.com wrote: > for i := 0; i > 5; i++ { > // handle a single message > n, err := c.Read(buf) > if err == io.EOF { > break > } > fmt.Fprintf(c, "Message Count %d, Data %s", i+1, buf[:n]) >
I will point out that it's possible for io.Read to return valid data *and* an error (including io.EOF). See https://golang.org/pkg/io/#Reader *"When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == EOF or err == nil. The next Read should return 0, EOF."* So perhaps you want something more like this: n, err := c.Read(buf) if n > 0 { fmt.Fprintf(c, "Message Count %d, Data %s", i+1, buf[:n]) } if err == io.EOF { break } if err != nil { fmt.Fprintf("Error: %s", err) break } Note that TCP is stream-oriented, so the number of bytes returned from Read > is not at all guaranteed to match the number of bytes the client sent. The > returned data can be part of one or more messages. You need some other > mechanism to divide the data received into messages. For example you might > want to read a line at a time instead. > That's critical. Messages need to be delimited somehow. Some protocols send a length followed by that number of bytes of data. Note that the JSON encoder/decoder in go supports sending objects one after the other - that is, the structure of a JSON object performs the delineation. After the start of an object '{' the decoder will keep consuming data until it gets the matching close '}' -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/f7aa702c-80e2-4c2c-a269-a88d4cf43680n%40googlegroups.com.