problem exchanging binary data over TCP

660 views
Skip to first unread message

Christopher Wicklein

unread,
Mar 7, 2010, 10:20:13 AM3/7/10
to golang-nuts
Greetings--

I'm trying to write a bit of Go to exchange binary data over a TCP connection.  The client connects to the server and writes an int32 in network byte order then reads back an int32 in network byte order.  The following code will compile but does not seem to work.  The key problem seems to be that the buffer doesn't contain the binary representation of xxx in network byte order (fmt.Printf shows an empty slice), but another concern is how read knows to stop reading at four bytes.  Does the size of the slice tell Read what to do?  There are other matters related to socket options which are pretty well documented, I'll start playing with those on my own once the blocking exchange works.

type byteSlice []byte

func (p *byteSlice) Write(data []byte) (n int, err os.Error) {
slice := *p
*p = slice
return len(data), nil
}

...

var buffer byteSlice
var xxx int32 = 1

binary.Write(&buffer, binary.BigEndian, xxx);
n, err := conn.Write(buffer)
if n != 4 {
// fail here
}
nn, err := conn.Read(buffer)
if nn != 4 {
// fail here
}


Christopher Wicklein <chr...@wicklein.org>

David Roundy

unread,
Mar 7, 2010, 10:41:34 AM3/7/10
to Christopher Wicklein, golang-nuts
On Sun, Mar 7, 2010 at 7:20 AM, Christopher Wicklein
<chr...@wicklein.org> wrote:
> Greetings--
> I'm trying to write a bit of Go to exchange binary data over a TCP
> connection.  The client connects to the server and writes an int32 in
> network byte order then reads back an int32 in network byte order.  The
> following code will compile but does not seem to work.  The key problem
> seems to be that the buffer doesn't contain the binary representation of xxx
> in network byte order (fmt.Printf shows an empty slice), but another concern
> is how read knows to stop reading at four bytes.  Does the size of the slice
> tell Read what to do?

Yes, this is the problem. It ought to work if you use slice with room
for some data. Try changing

> var buffer byteSlice

to

var buffer byteSlice = make([]byte, 4)

and it should read four bytes at a time (instead of zero bytes).

David Roundy (who didn't actually test this)

Daniel Smith

unread,
Mar 7, 2010, 10:41:48 AM3/7/10
to Christopher Wicklein, golang-nuts
I assume you "buffer = make([]byte, size)" somewhere?

It's unclear to me what "slice := *p; *p = slice" accomplishes.

You should consider skipping your buffer entirely and doing things like this:

err := binary.Write(conn, binary.BigEndian, xxx)

Since binary.Write takes an io.Writer and conn is such an animal. Same with your read. And binary.Write/Read know how many bytes to produce/consume based on the type you ask them to write/read.
--
Daniel Smith
http://www.schaumburggoclub.org/
Reply all
Reply to author
Forward
0 new messages