net package usage

100 views
Skip to first unread message

Hunter F

unread,
Nov 15, 2012, 2:10:43 AM11/15/12
to golan...@googlegroups.com
I've been having trouble wrapping my head around around a problem I've been having with the standard net package. 

I want to read n bytes at a time of a socket. In this case 10 bytes of a socket to google's webserver.


Running that I get:
Read: [72 84 84 80 47 49 46 48 32 50]
Read: [72 84 84 80 47 49 46 48 32 50]
Read: [72 84 84 80 47 49 46 48 32 50]
Read: [72 84 84 80 47 49 46 48 32 50]
Read: [72 84 84 80 47 49 46 48 32 50]
Read: [72 84 84 80 47 49 46 48 32 50]
...
 Continuing on forever.

It appears buf is not changing for each iteration of the loop. The first 10 bytes of the server's response stays in the slice through each iteration of the loop.

I've tried using bufio package to wrap it but the problem remains the same.

Dave Cheney

unread,
Nov 15, 2012, 2:15:23 AM11/15/12
to Hunter F, golan...@googlegroups.com
You are ignoring the number of bytes returned from Read

http://golang.org/pkg/io/#Reader

You should reslice buf using the number of bytes actually read.

Cheers

Dave
> --
>
>

Volker Dobler

unread,
Nov 15, 2012, 2:19:19 AM11/15/12
to golan...@googlegroups.com
Not sure if this is the issue, but from http://golang.org/pkg/io/#Reader
 "It returns the number of bytes read (0 <= n <= len(p)) [...] 
Read conventionally returns what is available instead of waiting for more."

It seems as if your loop reads the first 10 bytes properly and then reads
only 0 bytes (thus not changing buf). Check the number of bytes read
and print only those.

Volker

DisposaBoy

unread,
Nov 15, 2012, 2:33:51 AM11/15/12
to golan...@googlegroups.com
two issues. one has already been given: you should not ignore the n return which tells you how much data was actually read. and the source of your infinite old data is that you're only doing one read. that is the pre-condition read . after that the pre-condition is never executed again and you there have an infinite loop on a variable that never changes

Ethan Burns

unread,
Nov 15, 2012, 8:09:40 AM11/15/12
to golan...@googlegroups.com
This for loop does one read, then loops as long as err == nil; it never reads again.
for _, err := conn.Read(buf); err == nil; {
fmt.Println("Read:", buf)
}

You probably wanted this:
for _, err := conn.Read(buf); err == nil; _, err := conn.Read(buf){
fmt.Println("Read:", buf)
}


Best,
Ethan

Ethan Burns

unread,
Nov 15, 2012, 8:10:16 AM11/15/12
to golan...@googlegroups.com
BTW, as others have said, you should always check the number of bytes read.

Best,
Ethan
Reply all
Reply to author
Forward
0 new messages