The protocol i am programming for sends a header of 8 bytes that contains a body length. My problem is dat c.Read(buf) is blocking. Can i read from the tcp connection non blocking ?
On Wednesday, March 31, 2021 at 9:08:48 AM UTC+2 Brian Candler wrote: > 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/321c86c3-bed6-4afa-9291-b925d6072f8bn%40googlegroups.com.