6

I'm trying to read a stream of info from a connection. I haven't written the server part of it, and don't have access to modifying the protocol (or else I would have made the protocol much friendlier)

I'm trying to write a service in Go that reads an arbitrary number of bytes into a buffer in a loop and passes it off to another handler (I also cannot modify this part)

This is my current setup

buf := make([]byte, 256)
for {
    n, err := conn.Read(buf)
    fmt.Println(string(buf))
    if err != nil || n== 0 {
        return
    }
    Handle(buf[:n])
}

This works fine when there are enough bytes to be read... However, at the end of the stream, there aren't 256 bytes that are readable. Is there any way to preserve my 256 byte buffer while Read() to gracefully return?

2
  • I'm not understand. What is a "gracefully return"? Is Handle function only takes 256 length bytes? Commented Jul 18, 2014 at 5:20
  • 2
    You aren't dealing with EOF properly - see the io.Reader docs - an EOF can be returned with n != 0. Not sure whether this is your problem though! Commented Jul 18, 2014 at 10:33

1 Answer 1

9

If you want to read the whole stream of the connection you could use:

   var b bytes.Buffer
   if _, err:= io.Copy(&b, conn); err != nil {
      return err
   }

   Handle(b.Bytes())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.