Correct use of bufio.Reader

237 views
Skip to first unread message

TH

unread,
Feb 5, 2023, 4:01:22 PM2/5/23
to golang-nuts
Hey,

I have a TCP client which reads data from server. Each message is ; delimited. I wonder what's the correct way to use bufio.Reader, as I'm getting empty messages.

reader := bufio.NewReader(conn)
for {
    msg, err := reader.ReadBytes(59) // ; as delimiter
    if err == nil {
        fmt.Printf("%v\n", string(msg))
    }
}

So sometimes I will get a msg that's only ";". I wonder if bufio.Reader can be re-used as I do it on my for loop? Or are there any handy packages that I could use to parse the ";" delimiter?

I tried to write my own parser, but somehow bufio.Reader is like 3-4x faster even I thought I had an optimized code.

Thanks
- TH

Axel Wagner

unread,
Feb 6, 2023, 1:12:17 AM2/6/23
to TH, golang-nuts
That code seems to be correct (except that you might want a `if err != nil { break }` in there). I would say the reason you get empty messages is because the other side is sending you empty messages.

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/e4c474c8-87b0-400d-9576-c26ad54f585en%40googlegroups.com.

kristo

unread,
Feb 6, 2023, 12:58:10 PM2/6/23
to golang-nuts
Some data might have been read even if err != nil. Maybe always printing
out msg could give you a hint?

Reply all
Reply to author
Forward
0 new messages